<?php

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

/**
 * Reading and changing stored credentials is its own capability.
 *
 * Not folded into console.view: every operator has that, and "can open the
 * console" must not mean "can read the payment key".
 */
return new class extends Migration
{
    public function up(): void
    {
        // Spatie caches the catalogue. Inserting rows without dropping it means
        // the Owner keeps getting 403 on the new page until the cache expires —
        // long after the deploy that was supposed to grant it.
        app(PermissionRegistrar::class)->forgetCachedPermissions();

        // Whether it was ours to create decides whether it is ours to remove:
        // rolling back must not delete a permission — and every role assignment
        // hanging off it — that existed before this migration ran.
        $exists = DB::table('permissions')->where('name', 'secrets.manage')->exists();

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

        // Owner only. Deliberately not granted to Admin: this is the one page
        // where the blast radius is someone else's money.
        $permission = DB::table('permissions')->where('name', 'secrets.manage')->value('id');
        $owner = DB::table('roles')->where('name', 'Owner')->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.
        //
        // up() reuses the permission and the grant when they already exist, so
        // by the time down() runs there is no way to tell what this migration
        // created from what it merely found. Taking a capability away that
        // somebody else granted is worse than leaving one in place, and this is
        // a grant to the Owner role — the account that would have to fix it.
        app(PermissionRegistrar::class)->forgetCachedPermissions();
    }
};
