<?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 AdminUserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $dealer = Dealer::query()
            ->where('code', config('mtt_tenant.default_dealer_code'))
            ->firstOrFail();
        $roleName = 'System Admin';
        $departmentCode = DepartmentRoleMap::departmentCodeForRole($roleName);
        $department = Department::query()
            ->where('dealer_id', $dealer->id)
            ->where('code', $departmentCode)
            ->firstOrFail();

        $email = env('INITIAL_ADMIN_EMAIL', 'Dawid@eaintelligence.co.za');
        $name = env('INITIAL_ADMIN_NAME', 'System Admin');
        $plainPassword = env('INITIAL_ADMIN_PASSWORD') ?: env('DEMO_USERS_PASSWORD');
        $existingUser = User::query()
            ->whereIn('email', [$email, 'admin@example.test'])
            ->first();

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

            if (!$existingUser) {
                $plainPassword = Str::password(20);
                $this->command?->warn("Generated INITIAL_ADMIN_PASSWORD for {$email}: {$plainPassword}");
            }
        }

        $attributes = [
            'dealer_id' => $dealer->id,
            'department_id' => $department->id,
            'name' => $name,
        ];

        if ($plainPassword) {
            $attributes['password'] = Hash::make($plainPassword);
        }

        $user = $existingUser ?? new User();
        $user->email = $email;
        $user->fill($attributes);
        $user->save();

        $registrar = app(PermissionRegistrar::class);
        $registrar->setPermissionsTeamId($dealer->id);
        $user->syncRoles([$roleName]);
        $registrar->setPermissionsTeamId(null);
        $registrar->forgetCachedPermissions();
    }
}
