<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\PermissionRegistrar;

/**
 * Giving away a subscription or a module is its own capability, not folded
 * into `customers.manage` (suspend/reactivate, impersonate — reversible,
 * low-stakes account administration). A grant creates real money-shaped rows
 * — an order, a contract, a running instance — for nothing or at a discount,
 * so the button needs its own gate rather than merely being hidden.
 *
 * Owner only, following secrets.manage's precedent: this is another page
 * where the blast radius is someone else's money.
 */
return new class extends Migration
{
    public function up(): void
    {
        app(PermissionRegistrar::class)->forgetCachedPermissions();

        $exists = DB::table('permissions')->where('name', 'customers.grant_plan')->exists();

        if (! $exists) {
            DB::table('permissions')->insert([
                'name' => 'customers.grant_plan', 'guard_name' => 'operator',
                'created_at' => now(), 'updated_at' => now(),
            ]);
        }

        $permission = DB::table('permissions')->where('name', 'customers.grant_plan')->value('id');
        $owner = DB::table('roles')->where('name', 'Owner')->where('guard_name', 'operator')->value('id');

        if ($permission && $owner) {
            DB::table('role_has_permissions')->updateOrInsert(
                ['permission_id' => $permission, 'role_id' => $owner],
            );
        }

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

    public function down(): void
    {
        // Deliberately removes nothing — see add_secrets_capability.php for
        // why: by the time down() runs there is no way to tell what this
        // migration created from what it merely found already there.
        app(PermissionRegistrar::class)->forgetCachedPermissions();
    }
};
