package admin_agent

import (
	"context"
	"database/sql"
	"strconv"
	"jnc-server/common/xerr"

	"github.com/pkg/errors"

	"jnc-server/app/main/api/internal/svc"
	"jnc-server/app/main/api/internal/types"
	"jnc-server/app/main/model"

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

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

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

func (l *AdminUpdateAgentConfigLogic) AdminUpdateAgentConfig(req *types.AdminUpdateAgentConfigReq) (resp *types.AdminUpdateAgentConfigResp, err error) {
	// 系统简化：移除等级加成、升级费用、升级返佣、直接上级返佣配置、免税额度
	// 只保留佣金冻结配置和税率配置

	configTypeForKey := func(key string) string {
		switch key {
		case "commission_freeze_ratio", "commission_freeze_threshold", "commission_freeze_days":
			return "commission_freeze"
		case "tax_rate":
			return "tax"
		default:
			return "other"
		}
	}

	updateConfig := func(key string, value *float64) error {
		if value == nil {
			return nil
		}
		valStr := strconv.FormatFloat(*value, 'f', -1, 64)
		config, err := l.svcCtx.AgentConfigModel.FindOneByConfigKey(l.ctx, key)
		if err != nil {
			if errors.Is(err, model.ErrNotFound) {
				cfg := &model.AgentConfig{
					ConfigKey:   key,
					ConfigValue: valStr,
					ConfigType:  configTypeForKey(key),
					Description: sql.NullString{},
					DeleteTime:  sql.NullTime{},
					Version:     0,
				}
				_, insErr := l.svcCtx.AgentConfigModel.Insert(l.ctx, nil, cfg)
				if insErr != nil {
					return errors.Wrapf(insErr, "创建配置失败, key: %s", key)
				}
				return nil
			}
			return errors.Wrapf(err, "查询配置失败, key: %s", key)
		}
		config.ConfigValue = valStr
		if uErr := l.svcCtx.AgentConfigModel.UpdateWithVersion(l.ctx, nil, config); uErr != nil {
			if errors.Is(uErr, model.ErrNoRowsUpdate) {
				latestByKey, reErr := l.svcCtx.AgentConfigModel.FindOneByConfigKey(l.ctx, key)
				if reErr != nil {
					if errors.Is(reErr, model.ErrNotFound) {
						cfg := &model.AgentConfig{
							ConfigKey:   key,
							ConfigValue: valStr,
							ConfigType:  configTypeForKey(key),
							Description: sql.NullString{},
							DeleteTime:  sql.NullTime{},
							Version:     0,
						}
						_, insErr := l.svcCtx.AgentConfigModel.Insert(l.ctx, nil, cfg)
						if insErr != nil {
							return errors.Wrapf(insErr, "创建配置失败, key: %s", key)
						}
						return nil
					}
					return errors.Wrapf(reErr, "查询最新配置失败, key: %s", key)
				}
				latestByKey.ConfigValue = valStr
				return l.svcCtx.AgentConfigModel.UpdateWithVersion(l.ctx, nil, latestByKey)
			}
			return uErr
		}
		return nil
	}

	// 更新佣金冻结配置
	if req.CommissionFreeze != nil {
		if err := updateConfig("commission_freeze_ratio", &req.CommissionFreeze.Ratio); err != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "更新佣金冻结比例失败, %v", err)
		}
		if err := updateConfig("commission_freeze_threshold", &req.CommissionFreeze.Threshold); err != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "更新佣金冻结阈值失败, %v", err)
		}
		// 更新解冻天数（整数类型）
		if req.CommissionFreeze.Days > 0 {
			daysFloat := float64(req.CommissionFreeze.Days)
			if err := updateConfig("commission_freeze_days", &daysFloat); err != nil {
				return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "更新佣金冻结解冻天数失败, %v", err)
			}
		}
	}

	// 更新税费配置
	if err := updateConfig("tax_rate", req.TaxRate); err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "更新税率失败, %v", err)
	}

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