<?php

namespace App\Services;

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

class DealerProvisioner
{
    /**
     * Provision built-in users for a newly created dealer.
     */
    public function provisionForDealer(Dealer $dealer): void
    {
        $templates = config('mtt_builtin_users', []);

        if ($templates === []) {
            return;
        }

        /** @var PermissionRegistrar $registrar */
        $registrar = app(PermissionRegistrar::class);
        $registrar->setPermissionsTeamId($dealer->id);

        foreach ($templates as $template) {

            $emailLocal = $template['email_local'] ?? null;
            if (!$emailLocal) {
                continue;
            }

            // There is currently no dealer-specific domain column, so use a stable
            // fallback pattern based on dealer code for now.
            $email = sprintf(
                '%s+%s@%s',
                $emailLocal,
                $dealer->code ?? ('dealer-'.$dealer->id),
                config('mail.from.address', 'admin@example.test')
            );

            $departmentCode = $template['department_code'] ?? null;
            $departmentId = null;

            if ($departmentCode) {
                $departmentId = Department::query()
                    ->where('dealer_id', $dealer->id)
                    ->where('code', $departmentCode)
                    ->value('id');
            }

            $user = User::query()
                ->where('email', $email)
                ->first();

            if (!$user) {
                $user = new User();
                $user->email = $email;
                $user->dealer_id = $dealer->id;
            }

            $user->name = $template['name'] ?? 'Dealer';
            $user->surname = $template['surname'] ?? 'Administrator';
            $user->department_id = $departmentId;
            $user->password = Hash::make(Str::password(16));
            $user->force_password_change = true;
            $user->is_disabled = false;
            $user->save();

            $roles = (array) ($template['roles'] ?? []);
            if ($roles !== []) {
                $user->syncRoles($roles);
            }
        }

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

