package repository

import (
	"context"

	"gorm.io/gorm"

	"github.com/user-management-system/internal/domain"
)

// PasswordHistoryRepository 密码历史记录数据访问层
type PasswordHistoryRepository struct {
	db *gorm.DB
}

// NewPasswordHistoryRepository 创建密码历史记录数据访问层
func NewPasswordHistoryRepository(db *gorm.DB) *PasswordHistoryRepository {
	return &PasswordHistoryRepository{db: db}
}

// Create 创建密码历史记录
func (r *PasswordHistoryRepository) Create(ctx context.Context, history *domain.PasswordHistory) error {
	return r.db.WithContext(ctx).Create(history).Error
}

// GetByUserID 获取用户的密码历史记录（最近 N 条，按时间倒序）
func (r *PasswordHistoryRepository) GetByUserID(ctx context.Context, userID int64, limit int) ([]*domain.PasswordHistory, error) {
	var histories []*domain.PasswordHistory
	err := r.db.WithContext(ctx).
		Where("user_id = ?", userID).
		Order("created_at DESC").
		Limit(limit).
		Find(&histories).Error
	return histories, err
}

// DeleteOldRecords 删除超过 keepCount 条的旧记录（保留最新的 keepCount 条）
func (r *PasswordHistoryRepository) DeleteOldRecords(ctx context.Context, userID int64, keepCount int) error {
	// 找出要保留的最后一条记录的 ID
	var ids []int64
	err := r.db.WithContext(ctx).
		Model(&domain.PasswordHistory{}).
		Where("user_id = ?", userID).
		Order("created_at DESC").
		Limit(keepCount).
		Pluck("id", &ids).Error
	if err != nil {
		return err
	}
	if len(ids) == 0 {
		return nil
	}

	// 删除不在保留列表中的记录
	return r.db.WithContext(ctx).
		Where("user_id = ? AND id NOT IN ?", userID, ids).
		Delete(&domain.PasswordHistory{}).Error
}
