<?php

use App\Models\Instance;
use App\Support\ProvisioningSettings;
use App\Support\Settings;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Log;

/**
 * Puts customer instances on their own registrable domain.
 *
 * The zone has been a setting all along, and saying "change it in the console"
 * has now been said four times without the thing actually changing — which is
 * a fair complaint. An installation that has nothing to migrate should simply
 * arrive on the new zone.
 *
 * Guarded by exactly the condition `clupilot:check-zone` reports on: with no
 * instance in service there is nothing carrying the old name — no DNS record,
 * no certificate, no trusted_domains entry — so the change is free. With even
 * one, this does nothing and says so: re-addressing a running Nextcloud is a
 * migration with an outage, and a migration is not the place to start one.
 */
return new class extends Migration
{
    private const OLD = 'clupilot.com';

    private const NEW = 'clupilot.cloud';

    public function up(): void
    {
        $current = ProvisioningSettings::dnsZone();

        // Somebody else's installation, or one already moved. Not ours to
        // touch — the whole point of the zone being a setting is that another
        // operator may run this on their own domain.
        if ($current !== self::OLD) {
            return;
        }

        $inService = Instance::query()
            ->whereIn('status', ['active', 'provisioning', 'cancellation_scheduled'])
            ->count();

        if ($inService > 0) {
            Log::warning('Instance zone left on '.self::OLD.': '.$inService.' instance(s) in service carry it in DNS, certificates and trusted_domains. Run clupilot:check-zone and plan a window.');

            return;
        }

        Settings::set('provisioning.dns_zone', self::NEW);
    }

    public function down(): void
    {
        if (ProvisioningSettings::dnsZone() === self::NEW) {
            Settings::set('provisioning.dns_zone', self::OLD);
        }
    }
};
