// internal/services/archive_service.go
package services

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

	"gorm.io/gorm"
)

type ArchiveService struct {
	archiveRepo  *repositories.ArchiveRepository
	auditLogRepo *repositories.AuditLogRepository
}

func NewArchiveService(db *gorm.DB) *ArchiveService {
	return &ArchiveService{
		archiveRepo:  repositories.NewArchiveRepository(db),
		auditLogRepo: repositories.NewAuditLogRepository(db),
	}
}

// GetAllArchives gets all archived items
func (s *ArchiveService) GetAllArchives(page, limit int, reason, search string) ([]models.ArchiveResponse, int64, error) {
	archives, total, err := s.archiveRepo.FindAll(page, limit, reason, search)
	if err != nil {
		return nil, 0, err
	}

	var responses []models.ArchiveResponse
	for _, archive := range archives {
		responses = append(responses, archive.ToResponse())
	}

	return responses, total, nil
}

// GetArchiveByID gets archive by ID
func (s *ArchiveService) GetArchiveByID(id uint) (*models.Archive, error) {
	return s.archiveRepo.FindByID(id)
}

// GetArchiveByItemID gets archive by original item ID
func (s *ArchiveService) GetArchiveByItemID(itemID uint) (*models.Archive, error) {
	return s.archiveRepo.FindByItemID(itemID)
}

// GetArchiveStats gets archive statistics
func (s *ArchiveService) GetArchiveStats() (map[string]interface{}, error) {
	stats := make(map[string]interface{})

	// Count by reason
	expiredCount, err := s.archiveRepo.CountByReason(models.ArchiveReasonExpired)
	if err != nil {
		return nil, err
	}
	stats["expired"] = expiredCount

	caseClosedCount, err := s.archiveRepo.CountByReason(models.ArchiveReasonCaseClosed)
	if err != nil {
		return nil, err
	}
	stats["case_closed"] = caseClosedCount

	stats["total"] = expiredCount + caseClosedCount

	return stats, nil
}