<?php

namespace Database\Seeders;

use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class DatabaseSeeder extends Seeder
{
    use WithoutModelEvents;

    public function run(): void
    {
        $this->call(RolePermissionSeeder::class);
        $this->call(ModuleSeeder::class);
        $this->call(StoreGroupSeeder::class);
        $this->call(StoreSeeder::class);
        $this->call(OrderLookupsSeeder::class);
        $this->call(CostaRicaGeoSeeder::class);
       // $this->call(OrderSeeder::class);

        // Admin
        $admin = User::query()->firstOrCreate(
            ['email' => 'test@example.com'],
            [
                'name' => 'Test User',
                'password' => Hash::make('password'),
                'is_active' => true,
            ],
        );

        // Si ya existía, asegura estado/nombre y que tenga password
        $admin->forceFill(['name' => 'Test User', 'is_active' => true])->save();
        if (blank($admin->password)) {
            $admin->forceFill(['password' => Hash::make('password')])->save();
        }
        $admin->syncRoles(['administrador']);

        // Usuarios por rol (password: password)
        $seedUsers = [
            ['email' => 'logistica@example.com',     'name' => 'Usuario Logística',   'role' => 'logística'],
            ['email' => 'operador@example.com',      'name' => 'Usuario Operador',    'role' => 'operador'],
            ['email' => 'tienda@example.com',        'name' => 'Usuario Tienda',      'role' => 'tienda'],
            ['email' => 'sololectura@example.com',   'name' => 'Usuario Solo Lectura','role' => 'solo lectura'],
        ];

        foreach ($seedUsers as $data) {
            $user = User::query()->firstOrCreate(
                ['email' => $data['email']],
                [
                    'name' => $data['name'],
                    'password' => Hash::make('password'),
                    'is_active' => true,
                ],
            );

            $user->forceFill(['name' => $data['name'], 'is_active' => true])->save();
            if (blank($user->password)) {
                $user->forceFill(['password' => Hash::make('password')])->save();
            }

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