<?php

namespace Database\Seeders;

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

class DatabaseSeeder extends Seeder
{
    use WithoutModelEvents;

    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        $this->call([
            RoleSeeder::class,
            PermissionSeeder::class,
            LocationSeeder::class,
            BusinessTypeSeeder::class,
        ]);

        // Criar usuário admin padrão
        $admin = User::firstOrCreate(
            ['email' => 'admin@sinagem.com'],
            [
                'name' => 'Administrador',
                'email' => 'admin@sinagem.com',
                'type' => 'admin',
                'status' => true,
                'password' => bcrypt('admin123'),
            ]
        );

        // Atribuir role admin
        $adminRole = Role::where('name', 'admin')->first();
        if ($adminRole && ! $admin->roles()->where('role_id', $adminRole->id)->exists()) {
            $admin->roles()->attach($adminRole);
        }

        // Criar usuário fiscal de exemplo
        $fiscal = User::firstOrCreate(
            ['email' => 'fiscal@sinagem.com'],
            [
                'name' => 'Fiscal Silva',
                'email' => 'fiscal@sinagem.com',
                'type' => 'fiscal',
                'status' => true,
                'password' => bcrypt('fiscal123'),
            ]
        );

        $fiscalRole = Role::where('name', 'fiscal')->first();
        if ($fiscalRole && ! $fiscal->roles()->where('role_id', $fiscalRole->id)->exists()) {
            $fiscal->roles()->attach($fiscalRole);
        }

        // Criar fiscal profile
        Fiscal::firstOrCreate(
            ['user_id' => $fiscal->id],
            [
                'user_id' => $fiscal->id,
                'full_name' => 'João Silva',
                'badge_number' => 'F001',
                'phone' => '+244912345678',
                'status' => 'active',
            ]
        );
    }
}
