package repository

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

	"gorm.io/gorm"
)

// AuditRepo 审核记录数据访问
type AuditRepo struct {
	db *gorm.DB
}

// NewAuditRepo 构造函数
func NewAuditRepo(db *gorm.DB) *AuditRepo {
	return &AuditRepo{db: db}
}

// Create 创建审核提交
func (r *AuditRepo) Create(audit *model.AuditSubmission) error {
	return r.db.Create(audit).Error
}

// FindByID 按 ID 查找审核记录
func (r *AuditRepo) FindByID(id uint) (*model.AuditSubmission, error) {
	var audit model.AuditSubmission
	err := r.db.First(&audit, id).Error
	if err != nil {
		return nil, err
	}
	return &audit, nil
}

// FindPendingByUserAndType 查找用户某类型的待审记录（用于连续提交覆盖）
func (r *AuditRepo) FindPendingByUserAndType(userID uint, auditType string) (*model.AuditSubmission, error) {
	var audit model.AuditSubmission
	err := r.db.
		Where("user_id = ? AND audit_type = ? AND status = ?", userID, auditType, model.AuditStatusPending).
		First(&audit).Error
	if err != nil {
		return nil, err
	}
	return &audit, nil
}

// Update 全量更新审核记录
func (r *AuditRepo) Update(audit *model.AuditSubmission) error {
	return r.db.Save(audit).Error
}

// findAudits 构建审核列表查询
func (r *AuditRepo) findAudits(auditType, status string) *gorm.DB {
	q := r.db.Model(&model.AuditSubmission{})
	if auditType != "" {
		q = q.Where("audit_type = ?", auditType)
	}
	if status != "" {
		q = q.Where("status = ?", status)
	}
	return q
}

// ListAudits 分页查询审核列表
func (r *AuditRepo) ListAudits(auditType, status string, offset, limit int) ([]model.AuditSubmission, error) {
	var audits []model.AuditSubmission
	err := r.findAudits(auditType, status).
		Order("created_at DESC").
		Offset(offset).Limit(limit).
		Find(&audits).Error
	return audits, err
}

// CountAudits 统计审核记录总数
func (r *AuditRepo) CountAudits(auditType, status string) (int64, error) {
	var count int64
	err := r.findAudits(auditType, status).Count(&count).Error
	return count, err
}

// FindPendingByUserID 查找用户所有待审记录（用于个人中心提示）
func (r *AuditRepo) FindPendingByUserID(userID uint) ([]model.AuditSubmission, error) {
	var audits []model.AuditSubmission
	err := r.db.
		Where("user_id = ? AND status = ?", userID, model.AuditStatusPending).
		Find(&audits).Error
	return audits, err
}

// ExistsPendingByTypeAndValue 检查是否有同类型同值的待审记录（用于防重名提交）
// 排除指定 userID 的记录（允许同一用户覆盖自己的提交）
func (r *AuditRepo) ExistsPendingByTypeAndValue(auditType, newValue string, excludeUserID uint) (bool, error) {
	var count int64
	err := r.db.Model(&model.AuditSubmission{}).
		Where("audit_type = ? AND new_value = ? AND status = ? AND user_id != ?",
			auditType, newValue, model.AuditStatusPending, excludeUserID).
		Count(&count).Error
	return count > 0, err
}
