<?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
    {
        // Bảng đăng ký các module có thể phân quyền (auto từ Resource)
        Schema::create('permission_modules', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->string('module')->unique(); // contracts, payments, customers...
            $table->string('label'); // Hợp đồng, Thu tiền...
            $table->jsonb('actions'); // ["view","create","update","delete","restore","forceDelete","export"]
            $table->timestamps();
        });

        // Bảng mẫu nhóm (Role Template)
        Schema::create('role_templates', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->string('name'); // Sales, Kế toán, Admin...
            $table->text('description')->nullable();
            $table->jsonb('permissions')->default('{}'); // {"contracts":["view","create"], "payments":["view"]}
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });

        // Sửa users: thêm role_template_id, extra_permissions, excluded_permissions
        Schema::table('users', function (Blueprint $table) {
            $table->foreignUuid('role_template_id')->nullable()->constrained('role_templates')->nullOnDelete();
            $table->jsonb('extra_permissions')->default('[]');
            $table->jsonb('excluded_permissions')->default('[]');
        });
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropForeign(['role_template_id']);
            $table->dropColumn(['role_template_id', 'extra_permissions', 'excluded_permissions']);
        });

        Schema::dropIfExists('role_templates');
        Schema::dropIfExists('permission_modules');
    }
};
