package admin_product

import (
	"context"
	"database/sql"
	"jnc-server/app/main/api/internal/svc"
	"jnc-server/app/main/api/internal/types"
	"jnc-server/app/main/model"
	"jnc-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 {
		// 2.1 插入产品
		_, 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

		// 2.2 同步创建代理产品配置（使用默认值）
		agentProductConfig := &model.AgentProductConfig{
			Id:             uuid.NewString(),
			ProductId:      productId,
			BasePrice:      0.00,                          // 默认基础底价
			SystemMaxPrice: 9999.99,                       // 默认系统价格上限
			PriceThreshold: sql.NullFloat64{Valid: false}, // 默认不设阈值
			PriceFeeRate:   sql.NullFloat64{Valid: false}, // 默认不收费
		}

		_, err = l.svcCtx.AgentProductConfigModel.Insert(ctx, session, agentProductConfig)
		if err != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
				"创建代理产品配置失败, err: %v, productId: %s", err, productId)
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

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