// internal/repositories/archive_repo.go
package repositories

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

	"gorm.io/gorm"
)

type ArchiveRepository struct {
	db *gorm.DB
}

func NewArchiveRepository(db *gorm.DB) *ArchiveRepository {
	return &ArchiveRepository{db: db}
}

// Create creates a new archive record
func (r *ArchiveRepository) Create(archive *models.Archive) error {
	return r.db.Create(archive).Error
}

// FindByID finds archive by ID
func (r *ArchiveRepository) FindByID(id uint) (*models.Archive, error) {
	var archive models.Archive
	err := r.db.Preload("Category").Preload("Claimer").Preload("Claimer.Role").First(&archive, id).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("archive not found")
		}
		return nil, err
	}
	return &archive, nil
}

// FindAll returns all archived items with filters
func (r *ArchiveRepository) FindAll(page, limit int, reason, search string) ([]models.Archive, int64, error) {
	var archives []models.Archive
	var total int64

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

	// Apply filters
	if reason != "" {
		query = query.Where("archived_reason = ?", reason)
	}
	if search != "" {
    // GANTI ILIKE MENJADI LIKE
    query = query.Where("name LIKE ? OR location LIKE ?", "%"+search+"%", "%"+search+"%")
}

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

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

	return archives, total, nil
}

// FindByItemID finds archive by original item ID
func (r *ArchiveRepository) FindByItemID(itemID uint) (*models.Archive, error) {
	var archive models.Archive
	err := r.db.Where("item_id = ?", itemID).Preload("Category").Preload("Claimer").First(&archive).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("archive not found")
		}
		return nil, err
	}
	return &archive, nil
}

// Delete permanently deletes an archive
func (r *ArchiveRepository) Delete(id uint) error {
	return r.db.Unscoped().Delete(&models.Archive{}, id).Error
}

// CountByReason counts archives by reason
func (r *ArchiveRepository) CountByReason(reason string) (int64, error) {
	var count int64
	err := r.db.Model(&models.Archive{}).Where("archived_reason = ?", reason).Count(&count).Error
	return count, err
}