<?php

namespace App\Console\Commands;

use App\Models\BackupSetting;
use App\Services\BackupService;
use Illuminate\Console\Command;

/**
 * Runs daily regardless (see Kernel::schedule()) but only actually creates
 * a backup when BackupSetting says automated backups are on AND enough
 * time has passed for the configured frequency — the frequency itself
 * isn't a cron expression, it's a runtime setting the root admin toggles
 * from the SaaS control panel.
 */
class RunScheduledBackup extends Command
{
    protected $signature = 'backups:run-scheduled';

    protected $description = 'Create a backup if automated backups are enabled and due';

    public function handle(BackupService $backups): int
    {
        $settings = BackupSetting::current();

        if (!$settings->isDue()) {
            $this->info('No backup due.');

            return self::SUCCESS;
        }

        $filename = $backups->create();
        $settings->update(['last_run_at' => now()]);

        $this->info("Backup created: {$filename}");

        return self::SUCCESS;
    }
}
