<?php

namespace App\Console\Commands;

use App\Services\DatabaseBackupService;
use Illuminate\Console\Command;
use RuntimeException;

class RanchDatabaseBackupCommand extends Command
{
    protected $signature = 'ranch:backup-database
                            {--no-gzip : No comprimir el archivo}
                            {--keep= : Días de retención (default: config)}';

    protected $description = 'Genera respaldo SQL de la base de datos (requiere mysqldump en PATH)';

    public function handle(DatabaseBackupService $service): int
    {
        try {
            $backup = $service->createBackup(! $this->option('no-gzip'));
        } catch (RuntimeException $e) {
            $this->error($e->getMessage());

            return self::FAILURE;
        }

        if ($this->option('keep') !== null) {
            config(['ranch.backup.retention_days' => (int) $this->option('keep')]);
        }

        $sizeKb = round($backup['size_bytes'] / 1024, 1);
        $this->info("Respaldo: {$backup['path']} ({$sizeKb} KB)");

        return self::SUCCESS;
    }
}
