// internal/repositories/revision_log_repo.go
package repositories

import (
	"errors"
	"lost-and-found/internal/models"

	"gorm.io/gorm"
)

type RevisionLogRepository struct {
	db *gorm.DB
}

func NewRevisionLogRepository(db *gorm.DB) *RevisionLogRepository {
	return &RevisionLogRepository{db: db}
}

// Create creates a new revision log
func (r *RevisionLogRepository) Create(log *models.RevisionLog) error {
	return r.db.Create(log).Error
}

// FindByID finds revision log by ID
func (r *RevisionLogRepository) FindByID(id uint) (*models.RevisionLog, error) {
	var log models.RevisionLog
	err := r.db.Preload("Item").Preload("User").Preload("User.Role").First(&log, id).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("revision log not found")
		}
		return nil, err
	}
	return &log, nil
}

// FindByItem finds revision logs for an item
func (r *RevisionLogRepository) FindByItem(itemID uint, page, limit int) ([]models.RevisionLog, int64, error) {
	var logs []models.RevisionLog
	var total int64

	query := r.db.Model(&models.RevisionLog{}).Where("item_id = ?", itemID)

	// Count total
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// Get paginated results
	offset := (page - 1) * limit
	err := query.Preload("User").Preload("User.Role").
		Order("created_at DESC").
		Offset(offset).Limit(limit).Find(&logs).Error
	if err != nil {
		return nil, 0, err
	}

	return logs, total, nil
}

// FindAll returns all revision logs with filters
func (r *RevisionLogRepository) FindAll(page, limit int, userID *uint) ([]models.RevisionLog, int64, error) {
	var logs []models.RevisionLog
	var total int64

	query := r.db.Model(&models.RevisionLog{})

	// Apply filters
	if userID != nil {
		query = query.Where("user_id = ?", *userID)
	}

	// Count total
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// Get paginated results
	offset := (page - 1) * limit
	err := query.Preload("Item").Preload("User").Preload("User.Role").
		Order("created_at DESC").
		Offset(offset).Limit(limit).Find(&logs).Error
	if err != nil {
		return nil, 0, err
	}

	return logs, total, nil
}

// Log creates a new revision log entry (helper method)
func (r *RevisionLogRepository) Log(itemID, userID uint, fieldName, oldValue, newValue, reason string) error {
	return models.CreateRevisionLog(r.db, itemID, userID, fieldName, oldValue, newValue, reason)
}