<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('datacenters', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->string('code')->unique();   // e.g. fsn, hel — used by hosts.datacenter + placement
            $table->string('name');
            $table->string('location')->nullable();
            $table->boolean('active')->default(true);
            $table->timestamps();
        });

        // The host form now only offers codes from this table, so an existing
        // install must not upgrade into an empty list. Backfill every code
        // already referenced by a host, plus the previously hardcoded defaults.
        $names = ['fsn' => 'Falkenstein', 'hel' => 'Helsinki'];
        $locations = ['fsn' => 'DE', 'hel' => 'FI'];

        $codes = ['fsn', 'hel'];
        if (Schema::hasTable('hosts')) {
            $codes = array_values(array_unique(array_merge(
                $codes,
                DB::table('hosts')->whereNotNull('datacenter')->distinct()->pluck('datacenter')->all(),
            )));
        }

        $now = now();
        foreach ($codes as $code) {
            DB::table('datacenters')->insert([
                'uuid' => (string) Str::uuid(),
                'code' => $code,
                'name' => $names[$code] ?? Str::upper($code),
                'location' => $locations[$code] ?? null,
                'active' => true,
                'created_at' => $now,
                'updated_at' => $now,
            ]);
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('datacenters');
    }
};
