<?php

namespace App\Console\Commands;

use App\Jobs\BackupDatabaseJob;
use App\Models\Backup;
use App\Repositories\BackupRepository;
use Illuminate\Console\Command;

class CreateDatabaseBackup extends Command
{
    protected $signature = 'backup:database {--filename= : Optional SQL filename}';
    protected $description = 'Create a safe database backup immediately';

    public function handle(BackupRepository $repository): int
    {
        $filename = $this->option('filename') ?: 'backup_'.now()->format('YmdHis').'.sql';
        $backup = Backup::create(['filename' => $filename, 'status' => 'created']);
        (new BackupDatabaseJob($backup->id))->handle($repository, app(\App\Services\DatabaseBackupDumper::class));
        $backup->refresh();

        if ($backup->status !== 'completed') {
            $this->error('Backup failed: '.($backup->notes ?: 'Unknown error'));
            return self::FAILURE;
        }

        $this->info('Backup created: '.storage_path('app/backups/'.$backup->filename));
        return self::SUCCESS;
    }
}
