<?php

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

/**
 * User ↔ department assignments (spec §5 user_management "to_department:
 * many-to-many"). Backs the department data-scope: OrgScope::departmentIds()
 * mirrors the existing permitted_locations() pattern
 * (TENANCY-PERMISSIONS-AUDIT §2 "department scope").
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('org_user_departments')) {
            return;
        }

        Schema::create('org_user_departments', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('business_id');
            $t->unsignedInteger('user_id');
            $t->unsignedInteger('department_id');
            $t->boolean('is_primary')->default(false);
            $t->timestamps();

            $t->foreign('business_id')->references('id')->on('business')->onDelete('cascade');
            $t->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $t->foreign('department_id')->references('id')->on('clc_departments')->onDelete('cascade');
            $t->unique(['user_id', 'department_id']);
            $t->index(['business_id', 'user_id']);
            $t->index(['business_id', 'department_id']);
        });
    }

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