<?php

namespace Database\Seeders;

use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\PermissionRegistrar;

class OptionalAdminSeeder extends Seeder
{
    public function run(): void
    {
        $email = env('ADMIN_EMAIL');
        $password = env('ADMIN_PASSWORD');

        if (! is_string($email) || $email === '' || ! is_string($password) || $password === '') {
            return;
        }

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

        $user = User::query()->firstOrCreate(
            ['email' => $email],
            [
                'name' => 'Administrador',
                'password' => Hash::make($password),
            ]
        );

        // Si el usuario ya existía, firstOrCreate no actualiza la clave: alinear con .env al sembrar.
        $user->forceFill([
            'name' => 'Administrador',
            'password' => Hash::make($password),
            'email_verified_at' => now(),
        ])->save();

        $user->syncRoles(['administrador']);
    }
}
