package admin_product

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

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

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{
		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. 数据库操作
	result, err := l.svcCtx.ProductModel.Insert(l.ctx, nil, data)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"创建产品失败, err: %v, req: %+v", err, req)
	}

	// 3. 返回结果
	id, _ := result.LastInsertId()
	return &types.AdminCreateProductResp{Id: id}, nil
}
