package product

import (
	"context"

	"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"
	"git.apinb.com/bsm-sdk/core/service"
)

// 产品规格列表
func SpecFetch(ctx context.Context, in *pb.MallFetchRequest) (reply *pb.SpecReply, err error) {
	// parse authorization meta.
	_, err = service.ParseMetaCtx(ctx, &service.ParseOptions{RoleValue: "Mall_Admin"})
	if err != nil {
		return nil, err
	}

	if in.StoreIdentity == "" {
		return nil, errcode.ErrInvalidArgument
	}

	spec := make([]*models.MallProductSpec, 0)
	tx := impl.DBService.Model(&models.MallProductSpec{}).Where("store_identity = ?", in.StoreIdentity)
	if in.Keyword != "" {
		tx = tx.Where("keyword like ?", "%"+in.Keyword+"%")
	}
	err = tx.Order("created_at desc").Find(&spec).Error
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	return &pb.SpecReply{
		Count: int64(len(spec)),
		Data:  ModelToReplySpecList(spec),
	}, nil
}
