<?php

namespace Database\Seeders;

use App\Domain\Identity\Services\PermissionRegistry;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\PermissionRegistrar;

/**
 * Syncs the code-defined permission catalogue into the database. Idempotent:
 * safe to re-run after new modules add keys.
 */
class PermissionSeeder extends Seeder
{
    public function run(): void
    {
        $guard = config('auth.defaults.guard', 'web');

        DB::transaction(function () use ($guard) {
            foreach (PermissionRegistry::all() as $permission) {
                Permission::updateOrCreate(
                    ['name' => $permission['name'], 'guard_name' => $guard],
                    ['module' => $permission['module'], 'label' => $permission['label']],
                );
            }
        });

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