<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('association_roles', function (Blueprint $table) {
            $table->id();
            $table->foreignId('association_id')->constrained()->cascadeOnDelete();
            $table->string('name'); // e.g., "Executive", "Board Member", "Committee Chair"
            $table->string('slug')->nullable(); // e.g., "executive", "board-member"
            $table->text('description')->nullable();
            $table->boolean('can_access_admin_panel')->default(false);
            $table->json('permissions')->nullable(); // Future: granular permissions
            $table->integer('sort_order')->default(0); // For ordering roles
            $table->boolean('is_system_role')->default(false); // Built-in roles vs custom
            $table->boolean('is_active')->default(true);
            $table->timestamps();

            // Ensure unique role names per association
            $table->unique(['association_id', 'slug']);
        });

        // Update association_user pivot to reference role_id instead of role string
        Schema::table('association_user', function (Blueprint $table) {
            // Add new role_id column
            $table->foreignId('role_id')->nullable()->after('association_id')->constrained('association_roles')->nullOnDelete();

            // Keep old role column temporarily for migration
            // We'll remove it after data migration
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('association_roles');
    }
};
