<?php

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

/**
 * One customer per portal user, so impersonation and billing can't cross
 * customer boundaries. (customers.email is already unique, giving a 1:1
 * customer↔email mapping; this guarantees the same for the user link.)
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('customers', function (Blueprint $table) {
            $table->unique('user_id'); // nullable — SQL permits multiple NULLs
        });
    }

    public function down(): void
    {
        Schema::table('customers', function (Blueprint $table) {
            // MariaDB will not drop the last index a foreign key depends on,
            // and the constraint added one migration earlier is using this one.
            // So release it, drop the index, and put it back — re-adding builds
            // the index the constraint needs. Without this the whole suite of
            // migrations cannot be rolled back, which is how `migrate:fresh`
            // works.
            $table->dropForeign(['user_id']);
            $table->dropUnique(['user_id']);
            $table->foreign('user_id')->references('id')->on('users')->nullOnDelete();
        });
    }
};
