<?php

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

/**
 * ABAC rule store (spec §4 abac; TENANCY-PERMISSIONS-AUDIT §2 "custom scope /
 * ABAC overrides": rule rows role × entity × predicate, resolved by the
 * MedAccess policy service). role_id targets a concrete Spatie role;
 * role_key (e.g. 'doctor') targets the predefined role `{key}#{business_id}`.
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('org_access_rules')) {
            return;
        }

        Schema::create('org_access_rules', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('business_id');
            $t->unsignedInteger('role_id')->nullable();   // null = applies to role_key
            $t->string('role_key', 50)->nullable();       // e.g. 'doctor'
            $t->string('entity', 100);                    // e.g. 'patient', 'clinical_note', 'vitals'
            $t->string('rule_key', 100);                  // e.g. 'only_assigned', 'entity_ability', 'field_group'
            $t->json('rule_value')->nullable();
            $t->enum('effect', ['allow', 'deny']);
            $t->boolean('is_active')->default(true);
            $t->timestamps();

            $t->foreign('business_id')->references('id')->on('business')->onDelete('cascade');
            $t->index(['business_id', 'is_active']);
            $t->index(['business_id', 'entity']);
            $t->index(['business_id', 'role_key']);
        });
    }

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