<?php

namespace App\Services;

use App\Models\Driver;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class DriverAccountService
{
    /**
     * Create or update a User account for a driver
     */
    public function createOrUpdateDriverAccount(Driver $driver): User
    {
        $existingUser = User::where('email', $driver->email)
            ->where('role', 'driver')
            ->first();

        if ($existingUser) {
            // Update if exists
            $existingUser->update([
                'name' => $driver->name,
                'company_id' => $driver->company_id,
            ]);
            return $existingUser;
        }

        // Generate a temporary password
        $temporaryPassword = Str::random(12);

        // Create new user
        $user = User::create([
            'name' => $driver->name,
            'email' => $driver->email,
            'password' => Hash::make($temporaryPassword),
            'role' => 'driver',
            'company_id' => $driver->company_id,
        ]);

        return $user;
    }

    /**
     * Get temporary credentials for driver invitation (only on creation)
     */
    public function generateTemporaryCredentials(Driver $driver): array
    {
        $user = User::where('email', $driver->email)
            ->where('role', 'driver')
            ->first();

        if (!$user) {
            return [];
        }

        return [
            'email' => $driver->email,
            'temporary_password' => null, // Can't retrieve hashed password
            'needs_password_reset' => true,
        ];
    }
}
