<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Spatie\Permission\PermissionRegistrar;

class PermissionSeeder extends Seeder
{
    public function run(): void
    {
        app()[PermissionRegistrar::class]->forgetCachedPermissions();

        foreach (config('poskn.permission_definitions', []) as $name) {
            Permission::query()->firstOrCreate(
                ['name' => $name, 'guard_name' => 'web']
            );
        }

        $all = Permission::query()->where('guard_name', 'web')->orderBy('name')->get();

        Role::findByName('administrador', 'web')->syncPermissions($all);

        $gerenteDenied = config('poskn.gerente_denied_permissions', []);
        Role::findByName('gerente', 'web')->syncPermissions(
            $all->whereNotIn('name', $gerenteDenied)->values()
        );

        Role::findByName('medico', 'web')->syncPermissions(
            Permission::query()
                ->where('guard_name', 'web')
                ->whereIn('name', config('poskn.medico_permissions', []))
                ->orderBy('name')
                ->get()
        );

        Role::findByName('cajero', 'web')->syncPermissions(
            Permission::query()
                ->where('guard_name', 'web')
                ->whereIn('name', config('poskn.cajero_permissions', []))
                ->orderBy('name')
                ->get()
        );

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