package workers

import (
	"fmt"
	"log"
	"os/exec"
	"path/filepath"
	"time"

	"git.elijahkuntz.com/Elijah/drive/config"
	"git.elijahkuntz.com/Elijah/drive/database"
)

// StartBackupWorker runs a periodic SQLite backup task
func StartBackupWorker(cfg *config.Config, db *database.DB) {
	ticker := time.NewTicker(24 * time.Hour)
	go func() {
		for range ticker.C {
			runBackup(cfg, db)
		}
	}()
	
	// Also run one backup 5 minutes after startup if it hasn't been backed up today
	time.AfterFunc(5*time.Minute, func() {
		runBackup(cfg, db)
	})
}

func runBackup(cfg *config.Config, db *database.DB) {
	timestamp := time.Now().Format("20060102")
	backupFileName := fmt.Sprintf("drive_db_%s.sqlite", timestamp)
	backupPath := filepath.Join(cfg.BackupDir, backupFileName)

	// We use the sqlite3 CLI for a safe, online backup (it handles WAL mode correctly)
	cmd := exec.Command("sqlite3", cfg.DBPath, fmt.Sprintf(".backup '%s'", backupPath))
	
	if err := cmd.Run(); err != nil {
		log.Printf("❌ Database backup failed: %v", err)
		db.AddAuditLog("backup_failed", err.Error(), "system")
		return
	}

	log.Printf("✅ Database backed up successfully: %s", backupFileName)
	db.AddAuditLog("backup_success", backupFileName, "system")

	// Optional: Prune old backups (keep last 7 days)
	// Not fully implemented here to keep it simple, but would just delete files older than 7d in cfg.BackupDir
}
