<?php

namespace App\Http\Controllers\Api\Auth;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Auth\SessionTimeoutCheckRequest;
use App\Http\Requests\Auth\SessionTimeoutConfigRequest;
use App\Http\Requests\Auth\SessionTimeoutPingRequest;
use App\Http\Resources\Auth\SessionTimeoutConfigResource;
use App\Http\Resources\Auth\SessionTimeoutStatusResource;
use App\Services\Auth\SessionTimeoutConfigService;
use App\Services\Auth\SessionTimeoutService;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

class SessionTimeoutController extends BaseApiController
{
    public function __construct(
        private SessionTimeoutConfigService $configService,
        private SessionTimeoutService $timeoutService
    ) {
        parent::__construct();
    }

    public function config(SessionTimeoutConfigRequest $request): JsonResponse
    {
        $config = $this->configService->config();

        return $this->success([
            'config' => new SessionTimeoutConfigResource($config),
        ]);
    }

    public function check(SessionTimeoutCheckRequest $request): JsonResponse
    {
        $result = $this->timeoutService->checkTimeout();

        if (($result['status'] ?? '') === 'expired') {
            return $this->error(
                $result['message'] ?? 'Session expired.',
                Response::HTTP_UNAUTHORIZED,
                (new SessionTimeoutStatusResource($result))->toArray($request)
            );
        }

        return $this->success([
            'session' => new SessionTimeoutStatusResource($result),
        ]);
    }

    public function ping(SessionTimeoutPingRequest $request): JsonResponse
    {
        $result = $this->timeoutService->pingActivity();

        if (($result['status'] ?? '') === 'expired') {
            return $this->error(
                $result['message'] ?? 'Session expired.',
                Response::HTTP_UNAUTHORIZED,
                (new SessionTimeoutStatusResource($result))->toArray($request)
            );
        }

        return $this->success([
            'session' => new SessionTimeoutStatusResource($result),
        ]);
    }
}
