<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

/**
 * Enforce hosts.datacenter → datacenters.code at the database level so a
 * datacenter with hosts can never be deleted (restrictOnDelete), closing the
 * check-then-delete race in the admin console. All existing host codes were
 * backfilled into datacenters by 2026_07_25_090001.
 */
return new class extends Migration
{
    public function up(): void
    {
        // Safety net: ensure every referenced code exists before adding the FK.
        $now = now();
        $missing = DB::table('hosts')
            ->whereNotNull('datacenter')
            ->whereNotIn('datacenter', fn ($q) => $q->from('datacenters')->select('code'))
            ->distinct()->pluck('datacenter');
        foreach ($missing as $code) {
            DB::table('datacenters')->insert([
                'uuid' => (string) \Illuminate\Support\Str::uuid(),
                'code' => $code, 'name' => \Illuminate\Support\Str::upper($code),
                'active' => true, 'created_at' => $now, 'updated_at' => $now,
            ]);
        }

        Schema::table('hosts', function (Blueprint $table) {
            $table->foreign('datacenter')->references('code')->on('datacenters')->restrictOnDelete();
        });
    }

    public function down(): void
    {
        Schema::table('hosts', function (Blueprint $table) {
            $table->dropForeign(['datacenter']);
        });
    }
};
