package service

import (
	"metazone.cc/metalab/internal/common"
	"metazone.cc/metalab/internal/model"

	"gorm.io/gorm"
)

// review 通用审核操作
func (s *AuditService) review(reviewerID uint, submissionID uint, approved bool, reason string) error {
	// 1. 查审核记录
	submission, err := s.auditRepo.FindByID(submissionID)
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return common.ErrAuditNotFound
		}
		return err
	}

	// 2. 必须 pending
	if submission.Status != model.AuditStatusPending {
		return common.ErrAuditNotPending
	}

	// 3. 查审核人信息
	reviewer, err := s.userRepo.FindByID(reviewerID)
	if err != nil {
		return common.ErrUserNotFound
	}

	// 4. 标记审核结果
	submission.ReviewedBy = &reviewerID
	submission.ReviewerName = &reviewer.Username
	if approved {
		submission.Status = model.AuditStatusApproved
		// 更新 User 表对应字段
		if err := s.applyApproval(submission); err != nil {
			return err
		}
		// 通知用户审核通过
		if s.notifier != nil {
			s.notifier.NotifyAuditApproved(submission.UserID, submission.AuditType, submission.ID)
		}
	} else {
		submission.Status = model.AuditStatusRejected
		submission.RejectReason = &reason
		// 通知用户审核被拒（改名审核追加域能返还提示）
		if s.notifier != nil {
			reasonMsg := reason
			if submission.AuditType == model.AuditTypeUsername {
				reasonMsg += "。扣除的域能已被返还"
			}
			s.notifier.NotifyAuditRejected(submission.UserID, submission.AuditType, reasonMsg, submission.ID)
		}
		// 改名审核被拒 → 返还域能
		if submission.AuditType == model.AuditTypeUsername && s.energyRefundSvc != nil {
			_ = s.energyRefundSvc.RefundOnRenameReject(submission.UserID)
		}
	}
	return s.auditRepo.Update(submission)
}

// applyApproval 将审核通过的内容写入 User 表
// 用户名审批前再次检查冲突（防止提交到审批期间被其他用户抢占）
func (s *AuditService) applyApproval(submission *model.AuditSubmission) error {
	user, err := s.userRepo.FindByID(submission.UserID)
	if err != nil {
		return common.ErrUserNotFound
	}

	switch submission.AuditType {
	case model.AuditTypeUsername:
		exists, err := s.userRepo.ExistsByUsername(submission.NewValue)
		if err != nil {
			return err
		}
		if exists {
			return common.ErrUsernameTaken
		}
		user.Username = submission.NewValue
	case model.AuditTypeAvatar:
		user.Avatar = submission.NewValue
	case model.AuditTypeBio:
		user.Bio = submission.NewValue
	}
	if err := s.userRepo.Update(user); err != nil {
		return err
	}

	// 触发首次任务奖励（静默失败不影响主流程）
	if s.levelSvc != nil {
		switch submission.AuditType {
		case model.AuditTypeUsername:
			_, _, _ = s.levelSvc.CompleteTask(submission.UserID, "username")
		case model.AuditTypeAvatar:
			_, _, _ = s.levelSvc.CompleteTask(submission.UserID, "avatar")
		case model.AuditTypeBio:
			_, _, _ = s.levelSvc.CompleteTask(submission.UserID, "bio")
		}
	}

	return nil
}
