<?php

namespace Database\Seeders;

use App\Models\Department;
use App\Models\Role;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $adminRoleId = Role::where('slug', 'admin')->value('id');
        $userRoleId = Role::where('slug', 'user')->value('id');

        User::updateOrCreate(
            ['email' => 'admin@example.com'],
            [
                'name' => 'Admin User',
                'password' => Hash::make('password123'),
                'role_id' => $adminRoleId,
                'department_id' => null,
            ]
        );

        User::updateOrCreate(
            ['email' => 'user@example.com'],
            [
                'name' => 'Sales User',
                'password' => Hash::make('password123'),
                'role_id' => $userRoleId,
                'department_id' => null,
            ]
        );

        $this->call([
            DepartmentVisibilitySeeder::class,
            LeadVendorSeeder::class,
        ]);

        $salesDept = Department::where('slug', 'sales')->first();
        if ($salesDept && $userRoleId) {
            User::where('email', 'user@example.com')->update(['department_id' => $salesDept->id]);
        }

        $marketingDept = Department::where('slug', 'marketing')->first();
        if ($marketingDept && $userRoleId) {
            User::updateOrCreate(
                ['email' => 'marketing@example.com'],
                [
                    'name' => 'Marketing User',
                    'password' => Hash::make('password123'),
                    'role_id' => $userRoleId,
                    'department_id' => $marketingDept->id,
                ]
            );
        }
    }
}
