<?php
namespace Database\Seeders;

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

class RoleSeeder extends Seeder
{
    public function run(): void
    {
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        $permissions = [
            // Usuarios
            'users.index', 'users.create', 'users.edit', 'users.delete',
            // Departamentos
            'departments.index', 'departments.create', 'departments.edit', 'departments.delete',
            // Grupos de agentes
            'agent_groups.index', 'agent_groups.create', 'agent_groups.edit', 'agent_groups.delete',
            // Configuración
            'settings.index', 'settings.edit',
            // Reportes
            'reportes.index', 'reportes.export',
            // Dashboard
            'dashboard.admin', 'dashboard.operativo',
            // Auditoría
            'auditoria.index',
        ];

        foreach ($permissions as $permission) {
            Permission::firstOrCreate(['name' => $permission]);
        }

        // SUPERADMIN — acceso total
        $superadmin = Role::firstOrCreate(['name' => 'superadmin']);
        $superadmin->givePermissionTo(Permission::all());

        // ADMIN — operacional completo
        $admin = Role::firstOrCreate(['name' => 'admin']);
        $admin->givePermissionTo([
            'users.index', 'users.create', 'users.edit', 'users.delete',
            'departments.index', 'departments.create', 'departments.edit', 'departments.delete',
            'agent_groups.index', 'agent_groups.create', 'agent_groups.edit', 'agent_groups.delete',
            'settings.index', 'settings.edit',
            'reportes.index', 'reportes.export',
            'dashboard.admin', 'dashboard.operativo',
            'auditoria.index',
        ]);

        // JEFE DE SOPORTE
        $jefe = Role::firstOrCreate(['name' => 'jefe_soporte']);
        $jefe->givePermissionTo([
            'users.index',
            'departments.index',
            'agent_groups.index',
            'reportes.index', 'reportes.export',
            'dashboard.admin', 'dashboard.operativo',
        ]);

        // AGENTE
        $agente = Role::firstOrCreate(['name' => 'agente']);
        $agente->givePermissionTo([
            'users.index',
            'departments.index',
            'dashboard.operativo',
        ]);

        // USUARIO FINAL
        $usuario = Role::firstOrCreate(['name' => 'usuario']);
        $usuario->givePermissionTo([
            'dashboard.operativo',
        ]);

        // CONSULTOR (solo lectura)
        $consultor = Role::firstOrCreate(['name' => 'consultor']);
        $consultor->givePermissionTo([
            'users.index',
            'departments.index',
            'reportes.index',
            'dashboard.admin', 'dashboard.operativo',
        ]);
    }
}
