<?php

namespace App\Console\Commands;

use App\Services\DeploymentService;
use Illuminate\Console\Command;

/**
 * Freeze the currently-configured panel domain as the ACTIVE one for this container's
 * lifetime. Run by the entrypoint at every container start, so a dashboard domain change
 * takes effect on restart (and never mid-session).
 *
 * The snapshot itself is the readiness probe: it returns false until the setting can be
 * read authoritatively (database reachable AND the settings table migrated — neither is
 * guaranteed at startup: depends_on health isn't honored on host reboot, and on a fresh
 * install the app starts before install.sh migrates). We retry until it succeeds, and only
 * if it never does do we freeze the install-time env fallback — so a snapshot file always
 * exists and the active domain is never a live value that could shift after startup.
 */
class SnapshotDomain extends Command
{
    protected $signature = 'clusev:snapshot-domain {--tries=30}';

    protected $description = 'Snapshot the configured panel domain as the active serving domain (run at container start)';

    public function handle(DeploymentService $deployment): int
    {
        $tries = max(1, (int) $this->option('tries'));

        for ($i = 1; $i <= $tries; $i++) {
            if ($deployment->snapshotActiveDomain()) {
                $this->info('Active domain: '.($deployment->domain() ?? '(bare IP / HTTP)'));

                return self::SUCCESS;
            }

            if ($i < $tries) {
                sleep(1);
            }
        }

        // Settings never became readable in time. Keep any existing snapshot (last-known-good,
        // frozen); only if none exists, freeze the install-time env fallback — so the active
        // domain is always a FIXED snapshot and never falls back to a live value that could
        // change once the DB/migrations catch up (which would break the restart boundary).
        if ($deployment->hasSnapshot()) {
            $this->warn('Settings not reachable; kept the existing active-domain snapshot.');
        } else {
            $deployment->snapshotFallback();
            $this->warn('Settings not reachable; froze the install-time domain (dashboard override applies on the next ready restart).');
        }

        return self::SUCCESS;
    }
}
