<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('agent_delegation_grants', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('parent_agent_id')->constrained('agent_nodes')->cascadeOnDelete();
            $table->foreignId('child_agent_id')->constrained('agent_nodes')->cascadeOnDelete();
            $table->foreignId('menu_action_id')->constrained('admin_menu_actions')->cascadeOnDelete();
            $table->boolean('can_delegate')->default(false);
            $table->foreignId('granted_by')->nullable()->constrained('admin_users')->nullOnDelete();
            $table->timestamp('granted_at')->nullable();
            $table->timestamps();

            $table->unique(['child_agent_id', 'menu_action_id'], 'uk_agent_delegation_child_action');
            $table->index(['parent_agent_id', 'child_agent_id'], 'idx_agent_delegation_parent_child');
        });
    }

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