package admin_product

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

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

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

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

func (l *AdminUpdateProductLogic) AdminUpdateProduct(req *types.AdminUpdateProductReq) (resp *types.AdminUpdateProductResp, err error) {
	// 1. 查询记录是否存在
	record, err := l.svcCtx.ProductModel.FindOne(l.ctx, req.Id)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"查找产品失败, err: %v, id: %d", err, req.Id)
	}

	// 2. 更新字段
	if req.ProductName != nil {
		record.ProductName = *req.ProductName
	}
	if req.ProductEn != nil {
		record.ProductEn = *req.ProductEn
	}
	if req.Description != nil {
		record.Description = *req.Description
	}
	if req.Notes != nil {
		record.Notes = sql.NullString{String: *req.Notes, Valid: *req.Notes != ""}
	}
	if req.CostPrice != nil {
		record.CostPrice = *req.CostPrice
	}
	if req.SellPrice != nil {
		record.SellPrice = *req.SellPrice
	}

	// 3. 执行更新操作
	_, err = l.svcCtx.ProductModel.Update(l.ctx, nil, record)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"更新产品失败, err: %v, req: %+v", err, req)
	}

	// 4. 返回结果
	return &types.AdminUpdateProductResp{Success: true}, nil
}
