<?php

namespace Database\Seeders;

use App\Models\Department;
use App\Models\Dealer;
use App\Models\User;
use App\Support\DepartmentRoleMap;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use RuntimeException;
use Spatie\Permission\PermissionRegistrar;

class DemoUserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $dealer = Dealer::query()
            ->where('code', config('mtt_tenant.default_dealer_code'))
            ->firstOrFail();

        $demoUsers = [
            ['name' => 'Managing Director', 'email' => 'Allan@megatheron.co.za', 'role' => 'Managing Director', 'legacy_email' => 'demo.md@example.test'],
            ['name' => 'Branch Manager', 'email' => 'branch.manager@megatheron.co.za', 'role' => 'Branch Manager', 'legacy_email' => 'demo.branch.manager@example.test'],
            ['name' => 'Buyer', 'email' => 'buyer@megatheron.co.za', 'role' => 'Buyer', 'legacy_email' => 'demo.buyer@example.test'],
            ['name' => 'F&I', 'email' => 'fi@megatheron.co.za', 'role' => 'F&I', 'legacy_email' => 'demo.fi@example.test'],
            ['name' => 'Salesman', 'email' => 'salesmen@megatheron.co.za', 'role' => 'Salesman', 'legacy_email' => 'demo.salesmen@example.test'],
            ['name' => 'Financial Manager', 'email' => 'fin.manager@megatheron.co.za', 'role' => 'Financial Manager', 'legacy_email' => 'demo.fin.manager@example.test'],
            ['name' => 'Marketing', 'email' => 'marketing@megatheron.co.za', 'role' => 'Marketing', 'legacy_email' => 'demo.marketing@example.test'],
            ['name' => 'Stock Controller', 'email' => 'stock.controller@megatheron.co.za', 'role' => 'Stock Controller', 'legacy_email' => 'demo.stock.controller@example.test'],
            ['name' => 'Receptionist', 'email' => 'receptionist@megatheron.co.za', 'role' => 'Receptionist', 'legacy_email' => 'demo.receptionist@example.test'],
            ['name' => 'Driver', 'email' => 'driver@megatheron.co.za', 'role' => 'Driver', 'legacy_email' => 'demo.driver@example.test'],
            ['name' => 'Cleaner', 'email' => 'cleaner@megatheron.co.za', 'role' => 'Cleaner', 'legacy_email' => 'demo.cleaner@example.test'],
        ];

        $password = env('DEMO_USERS_PASSWORD');
        if (!$password && !app()->environment(['local', 'testing'])) {
            throw new RuntimeException('DEMO_USERS_PASSWORD must be set outside local/testing environments.');
        }

        if (!$password) {
            $password = Str::password(16);
            $this->command?->warn("Generated DEMO_USERS_PASSWORD: {$password}");
        }

        $registrar = app(PermissionRegistrar::class);
        $registrar->setPermissionsTeamId($dealer->id);

        foreach ($demoUsers as $demoUser) {
            $departmentCode = DepartmentRoleMap::departmentCodeForRole($demoUser['role']);
            $departmentId = Department::query()
                ->where('dealer_id', $dealer->id)
                ->where('code', $departmentCode)
                ->value('id');

            $emailsToMatch = array_filter([
                $demoUser['email'],
                $demoUser['legacy_email'] ?? null,
            ]);

            $user = User::query()->whereIn('email', $emailsToMatch)->first() ?? new User();
            $user->email = $demoUser['email'];
            $user->dealer_id = $dealer->id;
            $user->department_id = $departmentId;
            $user->name = $demoUser['name'];
            $user->password = Hash::make($password);
            $user->save();

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

        $registrar->setPermissionsTeamId(null);
        $registrar->forgetCachedPermissions();
    }
}
