<?php

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

/**
 * `instances.manage` — see and lift a security block sitting on a customer's
 * instance (App\Livewire\Admin\CustomerDetail, the "package" tab).
 *
 * No such capability existed: SecurityBlock and its release() method were
 * built in an earlier task, but nothing in the console could reach either yet
 * — this is that view, and it needs its own gate the way the matching
 * host-side section already leans on `hosts.manage`.
 *
 * Granted the same three roles as `instances.restart` (see that migration),
 * for the same reason stated there: a customer locked out by their own typo
 * is exactly the call Support answers the phone for, and an Admin who has to
 * fetch an Owner to press one button is an outage that lasts until somebody
 * answers.
 *
 * Guard `operator`: every capability in this application lives there since
 * 2026-07-29 (see move_rbac_to_operator_guard) — one created under `web`
 * would silently match nobody at all.
 */
return new class extends Migration
{
    public function up(): void
    {
        app(PermissionRegistrar::class)->forgetCachedPermissions();

        Permission::findOrCreate('instances.manage', 'operator');
        foreach (['Owner', 'Admin', 'Support'] as $role) {
            Role::findOrCreate($role, 'operator')->givePermissionTo('instances.manage');
        }

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

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