package admin_agent

import (
	"context"
	"errors"

	"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/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

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

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

func (l *AdminUpdateAgentCommissionStatusLogic) AdminUpdateAgentCommissionStatus(req *types.AdminUpdateAgentCommissionStatusReq) (resp *types.AdminUpdateAgentCommissionStatusResp, err error) {
	// 验证状态值
	if req.Status != 0 && req.Status != 1 && req.Status != 2 {
		return nil, xerr.NewErrMsg("无效的状态值，状态必须为0(已结算)、1(冻结中)或2(已取消)")
	}
	commission, err := l.svcCtx.AgentCommissionModel.FindOne(l.ctx, req.Id)
	if err != nil {
		if errors.Is(err, model.ErrNotFound) {
			return nil, xerr.NewErrMsg("佣金记录不存在")
		}
		return nil, err
	}

	// 检查状态是否允许修改
	if commission.Status == 0 {
		return nil, xerr.NewErrMsg("已结算的佣金记录不能修改状态")
	}
	if commission.Status == 2 {
		return nil, xerr.NewErrMsg("已取消的佣金记录不能修改状态")
	}

	// 开始事务
	err = l.svcCtx.AgentCommissionModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
		// 更新佣金状态
		commission.Status = req.Status
		err = l.svcCtx.AgentCommissionModel.UpdateWithVersion(ctx, session, commission)
		if err != nil {
			return err
		}

		// 查询代理钱包
		wallet, err := l.svcCtx.AgentWalletModel.FindOneByAgentId(ctx, commission.AgentId)
		if err != nil {
			return err
		}

		// 根据状态更新钱包
		if req.Status == 0 {
			// 解冻操作(状态改为已结算)：将金额添加到代理钱包余额
			wallet.Balance += commission.Amount
			wallet.FrozenBalance -= commission.Amount
		} else if req.Status == 2 {
			// 取消操作(状态改为已取消)：只扣减冻结金额
			wallet.FrozenBalance -= commission.Amount
		}

		err = l.svcCtx.AgentWalletModel.UpdateWithVersion(ctx, session, wallet)
		if err != nil {
			return err
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

	resp = &types.AdminUpdateAgentCommissionStatusResp{
		Success: true,
	}
	return
}
