<?php

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

/**
 * Splits the coarse `vpn.manage` into what it actually conflated:
 *
 *   vpn.view.all   — see every access, including other people's and host peers
 *   vpn.manage.all — create, assign, block and revoke any access
 *
 * Seeing is not managing, and neither implies holding someone else's private
 * key: downloading a stored config is owner-only and lives in VpnPeerPolicy,
 * not in a permission — ownership is record-level, permissions are elevated
 * capabilities.
 *
 * "Developer" is a view-only role. Writing code does not imply authority over
 * other people's access to the management network, so it deliberately gets no
 * manage capability.
 */
return new class extends Migration
{
    public function up(): void
    {
        app(PermissionRegistrar::class)->forgetCachedPermissions();

        Permission::findOrCreate('vpn.view.all', 'web');
        Permission::findOrCreate('vpn.manage.all', 'web');

        foreach (['Owner', 'Admin'] as $role) {
            Role::findOrCreate($role, 'web')->givePermissionTo(['vpn.view.all', 'vpn.manage.all']);
        }
        Role::findOrCreate('Developer', 'web')->syncPermissions(['console.view', 'vpn.view.all']);

        Permission::query()->where('name', 'vpn.manage')->delete();

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

    public function down(): void
    {
        app(PermissionRegistrar::class)->forgetCachedPermissions();

        Permission::findOrCreate('vpn.manage', 'web');
        foreach (['Owner', 'Admin'] as $role) {
            Role::findOrCreate($role, 'web')->givePermissionTo('vpn.manage');
        }
        Role::query()->where('name', 'Developer')->delete();
        Permission::query()->whereIn('name', ['vpn.view.all', 'vpn.manage.all'])->delete();

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