<?php

namespace App\Services\Auth;

use App\Config\SessionTimeout;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\URL;

class SessionTimeoutService
{
    public function __construct(
        private SessionActivityService $activityService
    ) {
    }

    public function checkTimeout(): array
    {
        if (!$this->activityService->hasLastActivity()) {
            return $this->expireSession();
        }

        $lastActivity = (int) $this->activityService->getLastActivity();
        $elapsed = time() - $lastActivity;

        if ($elapsed > SessionTimeout::TIMEOUT_DURATION) {
            return $this->expireSession();
        }

        if ($elapsed > SessionTimeout::WARNING_THRESHOLD) {
            return [
                'status' => 'warning',
                'time_remaining' => SessionTimeout::TIMEOUT_DURATION - $elapsed,
            ];
        }

        return [
            'status' => 'active',
            'time_remaining' => SessionTimeout::TIMEOUT_DURATION - $elapsed,
        ];
    }

    public function pingActivity(): array
    {
        if (
            !$this->activityService->hasLastActivity()
            || (time() - (int) $this->activityService->getLastActivity() > SessionTimeout::TIMEOUT_DURATION)
        ) {
            return $this->expireSession();
        }

        $this->activityService->setLastActivity(time());

        return [
            'status' => 'active',
            'time_remaining' => SessionTimeout::TIMEOUT_DURATION,
        ];
    }

    private function expireSession(): array
    {
        Log::info('Session expired due to inactivity.');
        $this->activityService->clearLastActivity();
        $this->activityService->invalidate();

        return [
            'status' => 'expired',
            'redirect' => URL::to('/login'),
            'message' => 'Your session has expired due to inactivity.',
            'time_remaining' => 0,
        ];
    }
}
