<?php

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

/**
 * Seed the operator RBAC catalogue in a migration (not a seeder) so the five
 * roles + capability permissions exist in every environment, including the
 * test database built by RefreshDatabase. Application code checks capabilities
 * (e.g. `hosts.manage`) via Laravel's Gate — never role names.
 */
return new class extends Migration
{
    public function up(): void
    {
        app(PermissionRegistrar::class)->forgetCachedPermissions();

        $capabilities = [
            'console.view',
            'hosts.manage',
            'datacenters.manage',
            'customers.manage',
            'customers.impersonate',
            'provisioning.retry',
            'provisioning.cancel',
            'billing.manage',
            'maintenance.manage',
            'staff.manage',
        ];
        foreach ($capabilities as $name) {
            Permission::findOrCreate($name, 'web');
        }

        $matrix = [
            'Owner' => $capabilities, // full control
            'Admin' => ['console.view', 'hosts.manage', 'datacenters.manage', 'customers.manage', 'customers.impersonate', 'provisioning.retry', 'provisioning.cancel', 'maintenance.manage'],
            'Support' => ['console.view', 'customers.manage', 'customers.impersonate', 'provisioning.retry'],
            'Billing' => ['console.view', 'billing.manage'],
            'Read-only' => ['console.view'],
        ];
        foreach ($matrix as $roleName => $perms) {
            Role::findOrCreate($roleName, 'web')->syncPermissions($perms);
        }

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

    public function down(): void
    {
        app(PermissionRegistrar::class)->forgetCachedPermissions();
        Role::query()->whereIn('name', ['Owner', 'Admin', 'Support', 'Billing', 'Read-only'])->delete();
        // Only the capabilities this migration introduced — never the whole catalogue.
        Permission::query()->whereIn('name', [
            'console.view', 'hosts.manage', 'datacenters.manage', 'customers.manage',
            'customers.impersonate', 'provisioning.retry', 'provisioning.cancel',
            'billing.manage', 'maintenance.manage', 'staff.manage',
        ])->delete();
    }
};
