<?php

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

/**
 * `instances.adminlogin` — obtain administrator credentials for a customer's
 * Nextcloud. Stronger than impersonation, which only borrows a portal session:
 * this hands over control of the customer's own installation, so Owner and
 * Admin only.
 */
return new class extends Migration
{
    public function up(): void
    {
        app(PermissionRegistrar::class)->forgetCachedPermissions();

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

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

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