<?php

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

/**
 * `instances.restart` — take a customer's machine down and bring it back.
 *
 * Weaker than `instances.adminlogin`, which hands over control of the customer's
 * own installation, and stronger than reading a list: it costs the customer
 * their cloud for a couple of minutes. Support holds it because support is who a
 * customer telephones to ask for exactly this, and a support agent who has to
 * fetch an Admin to press a button is an outage that lasts until somebody
 * answers.
 *
 * Guard `operator`: since the RBAC move (2026_07_29_100000) every permission in
 * this application lives there, and 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.restart', 'operator');
        foreach (['Owner', 'Admin', 'Support'] as $role) {
            Role::findOrCreate($role, 'operator')->givePermissionTo('instances.restart');
        }

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

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