<?php

namespace App\Console\Commands;

use App\Models\BackupSchedule;
use App\Services\BackupService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class RunScheduledBackups extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'backups:run-scheduled';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Rulează backup-urile programate care trebuie executate';

    protected $backupService;

    public function __construct(BackupService $backupService)
    {
        parent::__construct();
        $this->backupService = $backupService;
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Verificare backup-uri programate...');

        $schedules = BackupSchedule::where('enabled', true)
            ->whereNotNull('next_run_at')
            ->where('next_run_at', '<=', now())
            ->get();

        if ($schedules->isEmpty()) {
            $this->info('Nu există backup-uri programate de rulat.');
            return 0;
        }

        $this->info("Găsite {$schedules->count()} backup-uri de rulat.");

        foreach ($schedules as $schedule) {
            try {
                $this->info("Rulare backup: {$schedule->name}");

                // Creează backup-ul
                $backup = $this->backupService->createBackup([
                    'type' => $schedule->type,
                    'include_database' => in_array($schedule->type, ['full', 'database']),
                    'include_files' => in_array($schedule->type, ['full', 'zones']),
                    'created_by' => null, // System
                    'schedule_id' => $schedule->id,
                ]);

                // Marchează ca rulat și calculează următoarea rulare
                $schedule->markAsRun();

                // Curăță backup-urile vechi conform retenției
                $this->backupService->cleanupOldBackups($schedule->retention_days);

                $this->info("✓ Backup completat cu succes: {$backup->filename}");

                Log::info("Backup programat completat", [
                    'schedule_id' => $schedule->id,
                    'schedule_name' => $schedule->name,
                    'backup_id' => $backup->id,
                    'next_run' => $schedule->next_run_at,
                ]);

            } catch (\Exception $e) {
                $this->error("✗ Eroare la rularea backup-ului '{$schedule->name}': {$e->getMessage()}");

                Log::error("Backup programat eșuat", [
                    'schedule_id' => $schedule->id,
                    'schedule_name' => $schedule->name,
                    'error' => $e->getMessage(),
                ]);
            }
        }

        $this->info('Finalizat!');
        return 0;
    }
}
