package product

import (
	"context"
	"errors"

	"bsm/full/module/ec/mall/internal/impl"
	"bsm/full/module/ec/mall/internal/models"
	pb "bsm/full/module/ec/mall/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
	"gorm.io/gorm"
)

// Detail 通过产品序列获取产品详情
func ItemDetailBySerial(ctx context.Context, in *pb.StoreSerialRequest) (reply *pb.ListReply, err error) {
	if len(in.SerialId) == 0 || in.StoreIdentity == "" {
		return nil, errcode.ErrInvalidArgument
	}

	data := make([]*models.MallProduct, 0)
	err = impl.DBService.Preload("Spec").Preload("Images").Preload("Category").Where("store_identity=? and serial_id in ?", in.StoreIdentity, in.SerialId).Find(&data).Error

	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errcode.ErrNotFound(404, "Product")
		}
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}
	resp := ModelsToProductItems(data)

	return &pb.ListReply{
		Count: int64(len(resp)),
		Data:  resp,
	}, nil
}
