<?php

namespace App\Services;

use App\Models\LoginHistory;
use App\Models\User;
use App\Support\DeviceDetector;

class LoginHistoryService
{
    public function record(User $user, string $sessionId, ?string $ipAddress, ?string $userAgent): void
    {
        LoginHistory::query()->create([
            'user_id' => $user->id,
            'session_id' => $sessionId,
            'ip_address' => $ipAddress,
            'user_agent' => $userAgent,
            'device_name' => DeviceDetector::label($userAgent),
            'authenticated_at' => now(),
            'last_seen_at' => now(),
        ]);

        $user->forceFill([
            'last_login_ip' => $ipAddress,
            'last_login_at' => now(),
            'last_seen_at' => now(),
        ])->save();
    }

    public function touch(User $user, string $sessionId): void
    {
        LoginHistory::query()
            ->where('user_id', $user->id)
            ->where('session_id', $sessionId)
            ->latest('authenticated_at')
            ->first()
            ?->forceFill(['last_seen_at' => now()])
            ->save();

        $user->forceFill(['last_seen_at' => now()])->save();
    }
}
