<?php

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

/**
 * Publishing the processing agreement is a legal act, not an everyday one.
 *
 * Its own capability rather than settings.manage: whoever keeps the platform
 * running does not thereby decide what every customer is asked to agree to.
 *
 * Guard `operator`, not `web`. RBAC moved to the operator guard on 2026-07-29
 * (see that migration) — every capability written under `web` after it lands in
 * a guard nothing authenticates against, and the console answers 403 for a role
 * that visibly has the permission. Which is exactly what happened here first.
 */
return new class extends Migration
{
    public function up(): void
    {
        app(PermissionRegistrar::class)->forgetCachedPermissions();

        $permission = Permission::findOrCreate('dpa.manage', 'operator');

        foreach (['Owner', 'Admin'] as $role) {
            Role::findOrCreate($role, 'operator')->givePermissionTo($permission);
        }

        app(PermissionRegistrar::class)->forgetCachedPermissions();
    }

    public function down(): void
    {
        app(PermissionRegistrar::class)->forgetCachedPermissions();
        Permission::where('name', 'dpa.manage')->where('guard_name', 'operator')->delete();
        app(PermissionRegistrar::class)->forgetCachedPermissions();
    }
};
