package admin_agent

import (
	"context"
	"database/sql"
	"sim-server/common/xerr"

	"github.com/pkg/errors"

	"sim-server/app/main/api/internal/svc"
	"sim-server/app/main/api/internal/types"

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

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

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

func (l *AdminUpdateAgentProductConfigLogic) AdminUpdateAgentProductConfig(req *types.AdminUpdateAgentProductConfigReq) (resp *types.AdminUpdateAgentProductConfigResp, err error) {
	// 查询配置
	config, err := l.svcCtx.AgentProductConfigModel.FindOne(l.ctx, req.Id)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询产品配置失败, %v", err)
	}

	// 更新配置字段
	config.BasePrice = req.BasePrice
	config.SystemMaxPrice = req.PriceRangeMax
	
	// 价格阈值（可选）
	if req.PriceThreshold != nil {
		config.PriceThreshold = sql.NullFloat64{Float64: *req.PriceThreshold, Valid: true}
	} else {
		config.PriceThreshold = sql.NullFloat64{Valid: false}
	}
	
	// 提价手续费比例（可选）
	if req.PriceFeeRate != nil {
		config.PriceFeeRate = sql.NullFloat64{Float64: *req.PriceFeeRate, Valid: true}
	} else {
		config.PriceFeeRate = sql.NullFloat64{Valid: false}
	}

	// 更新配置
	if err := l.svcCtx.AgentProductConfigModel.UpdateWithVersion(l.ctx, nil, config); err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "更新产品配置失败, %v", err)
	}

	return &types.AdminUpdateAgentProductConfigResp{
		Success: true,
	}, nil
}
