<?php

namespace App\Services;

use App\Models\Client;
use Carbon\Carbon;

class ClientPresenceService
{
    /** Seconds without a visible-tab heartbeat before the client is offline. */
    public const ONLINE_THRESHOLD_SECONDS = 12;

    public function markSeen(Client $client, ?string $lastPage = null): Client
    {
        $client->last_seen_at = now();
        $client->is_online = true;

        if ($lastPage !== null && $lastPage !== '') {
            $client->last_page = $lastPage;
        }

        $client->save();

        return $client;
    }

    public function markAway(Client $client): Client
    {
        $client->is_online = false;
        $client->save();

        return $client;
    }

    public function resolvePresence(Client $client): array
    {
        $lastSeen = $client->last_seen_at;
        $secondsSince = null;

        if ($lastSeen instanceof Carbon) {
            $secondsSince = (int) abs(now()->diffInSeconds($lastSeen));
        }

        $freshHeartbeat = $lastSeen !== null
            && $secondsSince !== null
            && $secondsSince <= self::ONLINE_THRESHOLD_SECONDS;

        $online = (bool) $client->is_online && $freshHeartbeat;

        return [
            'online' => $online,
            'last_seen_at' => $lastSeen?->toIso8601String(),
            'seconds_since_seen' => $secondsSince,
            'last_page' => $client->last_page,
        ];
    }
}
