<?php

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

/**
 * Idempotent re-sync of all admin-guard permissions to the super-admin role.
 *
 * Production drift problem: AdminSeeder seeds super-admin with all permissions
 * existing AT SEED TIME. Permissions added later via migrations or feature PRs
 * (e.g. manage addon-modules, manage menus, manage pages, …) are NOT picked up
 * by super-admin unless this migration / equivalent runs.
 *
 * Safe to re-run; idempotent via syncPermissions() — only adds missing rows in
 * role_has_permissions, never removes anything.
 */
return new class extends Migration
{
    public function up(): void
    {
        $role = Role::where('name', 'super-admin')
            ->where('guard_name', 'admin')
            ->first();

        if (! $role) {
            // Role not yet seeded; AdminSeeder will create + populate fresh.
            return;
        }

        $allAdminPermissions = Permission::where('guard_name', 'admin')->pluck('id')->all();
        $role->permissions()->syncWithoutDetaching($allAdminPermissions);
    }

    public function down(): void
    {
        // No-op: removing permissions from super-admin would silently break
        // production access. If a permission needs to be revoked, do it
        // explicitly in a separate migration.
    }
};
