<?php

namespace Database\Seeders;

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

class RolesAndPermissionsSeeder extends Seeder
{
    public function run()
    {
        // Reset cached roles and permissions
        app()[PermissionRegistrar::class]->forgetCachedPermissions();

        // Create permissions
        $permissions = [
            'view projects', 'create projects', 'edit projects', 'delete projects',
            'assign users', 'upload layers', 'update progress', 'view reports', 'generate reports', 'manage all',
            'view inspections', 'create inspections', 'edit inspections', 'delete inspections', 'manage templates',
            'view tasks', 'create tasks', 'edit tasks', 'delete tasks', 'assign tasks', 'manage all tasks',
        ];
        foreach ($permissions as $perm) {
            Permission::firstOrCreate(['name' => $perm]);
        }

        // Create roles and assign permissions
        $admin = Role::firstOrCreate(['name' => 'Admin']);
        $admin->givePermissionTo(Permission::all());

        $supervisor = Role::firstOrCreate(['name' => 'Supervisor']);
        $supervisor->givePermissionTo([
            'view projects', 'upload layers', 'update progress',
            'view inspections', 'create inspections', 'edit inspections', 'delete inspections',
            'view tasks', 'create tasks', 'edit tasks', 'assign tasks',
        ]);

        $consultor = Role::firstOrCreate(['name' => 'Consultor']);
        $consultor->givePermissionTo(['view projects', 'view reports', 'view tasks']);

        $cliente = Role::firstOrCreate(['name' => 'Cliente']);
        $cliente->givePermissionTo(['view projects']);

        // Create default admin user (sin factory: los seeders de sistema no deben
        // depender de fakerphp/faker, que vive en require-dev).
        $user = User::firstOrCreate(
            ['email' => 'admin@email.com'],
            [
                'name' => 'Admin User',
                'password' => bcrypt('password'),
            ],
        );
        $user->assignRole('Admin');
    }
}
