<?php

use Illuminate\Database\Migrations\Migration;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

/**
 * PRC-398 / PRC-327 — seed `manage modules` super-permission + the five
 * per-family permissions consumed by the family-specific controllers
 * (`SmsModuleController`, `EmailModuleController`, …) once they ship.
 *
 * Granting now keeps RBAC drift checks (PRC-266) happy: routes referenced
 * in route files always have a matching permission row. The super-admin
 * role gets all six; granular roles can opt in later via admin UI.
 */
return new class extends Migration
{
    private array $permissions = [
        'manage modules',
        'manage sms modules',
        'manage email modules',
        'manage citizenship modules',
        'manage dns providers',
        'manage currency providers',
    ];

    public function up(): void
    {
        foreach ($this->permissions as $name) {
            Permission::firstOrCreate([
                'name' => $name,
                'guard_name' => 'admin',
            ]);
        }

        // Flush Spatie permission cache so new rows are immediately
        // visible to subsequent queries in this request and the running
        // queue worker.
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        $superAdmin = Role::where('name', 'super-admin')->where('guard_name', 'admin')->first();
        if ($superAdmin) {
            $superAdmin->givePermissionTo($this->permissions);
        }
    }

    public function down(): void
    {
        Permission::whereIn('name', $this->permissions)
            ->where('guard_name', 'admin')
            ->delete();

        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();
    }
};
