<?php

namespace App\Commands;

use App\Models\Control\TenantRecordModel;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;

/**
 * Batch job (same "loop every active tenant, setTenant() per iteration"
 * shape as every other scheduled command) meant to run once a day via
 * cron:
 *   php spark backup:run
 *
 * Unlike the AI features, this always runs for every active tenant —
 * there's no "backups off" toggle, since a rotating local copy is a
 * baseline safety net every hotel gets regardless of what they've
 * configured. Emailing a copy on top of that IS opt-in (Data Backup
 * page's own "Automated Backups" card) — BackupService checks that
 * setting itself, this command doesn't need to know about it.
 */
class RunBackup extends BaseCommand
{
    protected $group       = 'Backup';
    protected $name        = 'backup:run';
    protected $description = 'Backs up every active tenant\'s database — a local rotating copy always, plus email if the hotel has opted in.';

    public function run(array $params)
    {
        $tenants = (new TenantRecordModel())->where('status', 'active')->findAll();

        foreach ($tenants as $tenant) {
            $this->backupTenant($tenant);
        }
    }

    private function backupTenant(object $tenant): void
    {
        service('tenantContext')->setTenant($tenant);

        $result = service('backupService')->runForCurrentTenant();

        if (! $result['success']) {
            CLI::error("{$tenant->slug}: backup FAILED — {$result['error']}");

            return;
        }

        $size = round($result['fileSizeBytes'] / 1024, 1);
        $emailNote = $result['emailed'] ? ', emailed' : ($result['emailError'] ? ", email failed: {$result['emailError']}" : '');

        CLI::write("{$tenant->slug}: backed up ({$size} KB{$emailNote}).", 'green');
    }
}
