package agentrecharge

import (
	"context"
	"strings"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"

	approvalapp "github.com/break/junhong_cmp_fiber/internal/application/approval"
	walletapp "github.com/break/junhong_cmp_fiber/internal/application/wallet"
	"github.com/break/junhong_cmp_fiber/internal/model"
	"github.com/break/junhong_cmp_fiber/pkg/constants"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
)

// ApprovalDecisionHandler 将渠道无关审批终态应用到员工线下代充值业务。
type ApprovalDecisionHandler struct {
	db      *gorm.DB
	posting *walletapp.PostingService
}

// NewApprovalDecisionHandler 创建员工线下代充值审批终态消费者。
func NewApprovalDecisionHandler(db *gorm.DB, posting *walletapp.PostingService) *ApprovalDecisionHandler {
	return &ApprovalDecisionHandler{db: db, posting: posting}
}

// Handle 幂等处理标准审批终态；只有 approved 首次入账，其他终态不修改钱包。
func (h *ApprovalDecisionHandler) Handle(ctx context.Context, event approvalapp.TerminalDecisionEvent) error {
	if h == nil || h.db == nil || h.posting == nil {
		return errors.New(errors.CodeInternalError, "员工线下代充值审批终态能力未配置")
	}
	if event.BusinessType != constants.ApprovalBusinessTypeOfflineRecharge || event.BusinessID == 0 || event.InstanceID == 0 {
		return errors.New(errors.CodeInvalidParam, "员工线下代充值审批终态参数无效")
	}
	return h.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
		var record model.AgentRechargeRecord
		if err := tx.WithContext(ctx).Clauses(clause.Locking{Strength: "UPDATE"}).
			Where("id = ? AND payment_method = ?", event.BusinessID, constants.RechargeMethodOffline).
			First(&record).Error; err != nil {
			if err == gorm.ErrRecordNotFound {
				return errors.New(errors.CodeForbidden, "无权限操作该资源或资源不存在")
			}
			return errors.Wrap(errors.CodeDatabaseError, err, "锁定员工线下代充值申请失败")
		}
		if record.ApprovalInstanceID == nil || *record.ApprovalInstanceID != event.InstanceID {
			return errors.New(errors.CodeConflict, "线下代充值申请关联的审批实例不一致")
		}
		switch event.Decision {
		case constants.ApprovalDecisionApproved:
			return h.applyApproved(ctx, tx, &record, event)
		case constants.ApprovalDecisionRejected:
			return closeOfflineRecharge(ctx, tx, &record, constants.RechargeStatusRejected, "企业微信审批已拒绝")
		case constants.ApprovalDecisionCancelled:
			return closeOfflineRecharge(ctx, tx, &record, constants.RechargeStatusClosed, "企业微信审批已撤销")
		case constants.ApprovalDecisionDeleted:
			return closeOfflineRecharge(ctx, tx, &record, constants.RechargeStatusClosed, "企业微信审批已删除")
		case constants.ApprovalDecisionRevokedAfterApproved:
			return nil
		default:
			return errors.New(errors.CodeInvalidParam, "不支持的线下代充值审批终态")
		}
	})
}

func (h *ApprovalDecisionHandler) applyApproved(
	ctx context.Context,
	tx *gorm.DB,
	record *model.AgentRechargeRecord,
	event approvalapp.TerminalDecisionEvent,
) error {
	if record.Status != constants.RechargeStatusPending && record.Status != constants.RechargeStatusCompleted {
		return errors.New(errors.CodeInvalidStatus, "线下代充值申请状态不允许审批入账")
	}
	if record.Status == constants.RechargeStatusPending {
		result := tx.WithContext(ctx).Model(&model.AgentRechargeRecord{}).
			Where("id = ? AND status = ?", record.ID, constants.RechargeStatusPending).
			Updates(map[string]any{
				"status": constants.RechargeStatusCompleted, "paid_at": event.OccurredAt,
				"completed_at": event.OccurredAt, "updated_at": event.OccurredAt,
			})
		if result.Error != nil {
			return errors.Wrap(errors.CodeDatabaseError, result.Error, "完成线下代充值审批申请失败")
		}
		if result.RowsAffected != 1 {
			return errors.New(errors.CodeConflict, "线下代充值申请状态已变化")
		}
	}
	_, err := h.posting.PostInTx(ctx, tx, walletapp.PostingCommand{
		ShopID: record.ShopID, WalletID: record.AgentWalletID, Amount: record.Amount,
		ReferenceType: constants.ReferenceTypeTopup, ReferenceID: record.ID,
		TransactionType: constants.AgentTransactionTypeRecharge,
		UserID:          event.SubmitterAccountID, Creator: event.SubmitterAccountID,
		Remark: "企业微信审批通过线下充值", CorrelationID: event.CorrelationID,
	})
	return err
}

func closeOfflineRecharge(ctx context.Context, tx *gorm.DB, record *model.AgentRechargeRecord, status int, reason string) error {
	if record.Status == status {
		return nil
	}
	if record.Status != constants.RechargeStatusPending {
		return errors.New(errors.CodeInvalidStatus, "线下代充值申请状态不允许结束审批")
	}
	reason = strings.TrimSpace(reason)
	result := tx.WithContext(ctx).Model(&model.AgentRechargeRecord{}).
		Where("id = ? AND status = ?", record.ID, constants.RechargeStatusPending).
		Updates(map[string]any{"status": status, "rejection_reason": reason})
	if result.Error != nil {
		return errors.Wrap(errors.CodeDatabaseError, result.Error, "结束线下代充值审批申请失败")
	}
	if result.RowsAffected != 1 {
		return errors.New(errors.CodeConflict, "线下代充值申请状态已变化")
	}
	return nil
}

var _ approvalapp.BusinessDecisionHandler = (*ApprovalDecisionHandler)(nil)
