package admin_product

import (
	"context"
	"database/sql"
	"in-server/app/main/api/internal/svc"
	"in-server/app/main/api/internal/types"
	"in-server/app/main/model"
	"in-server/common/xerr"

	"github.com/google/uuid"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

type AdminCreateProductLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAdminCreateProductLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminCreateProductLogic {
	return &AdminCreateProductLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AdminCreateProductLogic) AdminCreateProduct(req *types.AdminCreateProductReq) (resp *types.AdminCreateProductResp, err error) {
	// 1. 数据转换
	data := &model.Product{
		Id:          uuid.NewString(),
		ProductName: req.ProductName,
		ProductEn:   req.ProductEn,
		Description: req.Description,
		Notes:       sql.NullString{String: req.Notes, Valid: req.Notes != ""},
		CostPrice:   req.CostPrice,
		SellPrice:   req.SellPrice,
	}

	// 2. 数据库操作（仅创建产品本身）
	var productId string
	err = l.svcCtx.ProductModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
		_, err := l.svcCtx.ProductModel.Insert(ctx, session, data)
		if err != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
				"创建产品失败, err: %v, req: %+v", err, req)
		}
		productId = data.Id
		return nil
	})

	if err != nil {
		return nil, err
	}

	// 3. 返回结果
	return &types.AdminCreateProductResp{Id: productId}, nil
}
