package core

import (
	"context"
	"log"
	"os"
	"path/filepath"

	"gitea.mrixs.me/minecraft-platform/backend/internal/database"
)

// FileJanitorService отвечает за очистку осиротевших файлов.
type FileJanitorService struct {
	ModpackRepo *database.ModpackRepository
	StoragePath string
}

// NewFileJanitorService создает новый экземпляр сервиса-уборщика.
func NewFileJanitorService(repo *database.ModpackRepository, storagePath string) *FileJanitorService {
	return &FileJanitorService{
		ModpackRepo: repo,
		StoragePath: storagePath,
	}
}

// CleanOrphanedFiles сканирует хранилище и удаляет файлы, отсутствующие в БД.
func (s *FileJanitorService) CleanOrphanedFiles(ctx context.Context) {
	log.Println("Janitor: Starting orphaned file cleanup...")

	liveHashes, err := s.ModpackRepo.GetAllFileHashes(ctx)
	if err != nil {
		log.Printf("Janitor: Error getting live hashes from DB: %v", err)
		return
	}

	diskFiles, err := os.ReadDir(s.StoragePath)
	if err != nil {
		log.Printf("Janitor: Error reading storage directory %s: %v", s.StoragePath, err)
		return
	}

	removedCount := 0
	for _, file := range diskFiles {
		if file.IsDir() {
			continue
		}

		fileName := file.Name()
		if _, isLive := liveHashes[fileName]; !isLive {
			filePath := filepath.Join(s.StoragePath, fileName)
			if err := os.Remove(filePath); err != nil {
				log.Printf("Janitor: Failed to remove orphaned file %s: %v", filePath, err)
			} else {
				log.Printf("Janitor: Removed orphaned file %s", filePath)
				removedCount++
			}
		}
	}

	log.Printf("Janitor: Cleanup complete. Removed %d orphaned files.", removedCount)
}
