package application

import (
	"fmt"
	"log"
	"os"
	"time"
)

func ParseDuration(s string) (time.Duration, error) {
	if s == "" {
		return 24 * time.Hour, nil // Default to 1 day
	}
	return time.ParseDuration(s)
}

func StartCleanupRoutine() {
	deleteAfterStr := os.Getenv("DELETE_FILES_AFTER")
	deleteAfter, err := ParseDuration(deleteAfterStr)
	if err != nil {
		log.Printf("Invalid DELETE_FILES_AFTER value '%s', using default 1 day: %v", deleteAfterStr, err)
		deleteAfter = 24 * time.Hour
	}

	log.Printf("File cleanup routine started, deleting files older than %v", deleteAfter)

	ticker := time.NewTicker(time.Hour) // Check every hour
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C:
			CleanupOldFiles(deleteAfter)
		}
	}
}

func CleanupOldFiles(maxAge time.Duration) {
	uploadsDir := os.Getenv("UPLOAD_DIR")
	if uploadsDir == "" {
		uploadsDir = "./uploads"
	}

	entries, err := os.ReadDir(uploadsDir)
	if err != nil {
		if !os.IsNotExist(err) {
			log.Printf("Error reading uploads directory: %v", err)
		}
		return
	}

	cutoffTime := time.Now().Add(-maxAge)
	deletedCount := 0

	for _, entry := range entries {
		if !entry.IsDir() {
			continue
		}

		dirPath := fmt.Sprintf("%s/%s", uploadsDir, entry.Name())
		info, err := entry.Info()
		if err != nil {
			log.Printf("Error getting info for directory %s: %v", dirPath, err)
			continue
		}

		if info.ModTime().Before(cutoffTime) {
			if err := os.RemoveAll(dirPath); err != nil {
				log.Printf("Error deleting directory %s: %v", dirPath, err)
			} else {
				deletedCount++
				log.Printf("Deleted old directory: %s", dirPath)
			}
		}
	}

	if deletedCount > 0 {
		log.Printf("Cleanup completed: deleted %d old directories", deletedCount)
	}
}