<?php

namespace Database\Seeders;

use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class RolePermissionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // database/seeders/RolePermissionSeeder.php

        // Crear rol de administrador
        $adminRole = Role::updateOrCreate(
            ['name' => 'admin'],
            //['description' => 'Administrador del sistema']
        );

        // Sincronizar todos los permisos con el rol admin
        $allPermissions = Permission::all();
        $adminRole->syncPermissions($allPermissions);

        $adminEmail = env('ADMIN_EMAIL', 'admin@example.com');
        $user = User::where('email', $adminEmail)->first();
        if ($user) {
            // Asignar rol solo si no lo tiene
            if (!$user->hasRole($adminRole)) {
                $user->assignRole($adminRole);
            }
        } else {
            // Crear solo si no existe
            User::create([
                'first_name' => 'Administrador',
                'username' => 'admin',
                'email' => 'admin@example.com',
                'password' => '12345678',
                'is_active' => true,
                'email_verified_at' => now()
            ])->assignRole($adminRole);
        }
    }
    
}
