<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('role_permissions', function (Blueprint $table) {
            $table->id();
            $table->string('role');
            $table->string('permission');
            $table->boolean('allowed')->default(true);
            $table->timestamps();
            $table->unique(['role', 'permission']);
            $table->index(['role', 'allowed']);
        });

        $now = now();
        $rows = [];
        $permissions = array_keys(config('permissions.permissions', []));

        foreach (config('permissions.defaults', []) as $role => $allowed) {
            $rolePermissions = in_array('*', $allowed, true) ? $permissions : $allowed;

            foreach ($rolePermissions as $permission) {
                $rows[] = [
                    'role' => $role,
                    'permission' => $permission,
                    'allowed' => true,
                    'created_at' => $now,
                    'updated_at' => $now,
                ];
            }
        }

        if ($rows !== []) {
            DB::table('role_permissions')->insert($rows);
        }
    }

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