<?php

namespace Tests\App\Controllers\Api;

use App\Controllers\Api\SessionTimeoutController;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Test\CIUnitTestCase;

class TestableSessionTimeoutController extends SessionTimeoutController
{
    protected function success($data = null, string $message = 'Success', int $code = ResponseInterface::HTTP_OK)
    {
        return ['data' => $data, 'message' => $message, 'code' => $code];
    }

    protected function error(string $message = 'An error occurred', int $code = ResponseInterface::HTTP_BAD_REQUEST, ?array $errors = null)
    {
        return ['message' => $message, 'code' => $code, 'errors' => $errors];
    }
}

class SessionTimeoutControllerTest extends CIUnitTestCase
{
    protected function tearDown(): void
    {
        parent::tearDown();
        session()->destroy();
    }

    public function testGetTimeoutConfigIncludesKeys()
    {
        $controller = new TestableSessionTimeoutController();
        $response = $controller->getTimeoutConfig();

        $this->assertSame(ResponseInterface::HTTP_OK, $response['code']);
        $this->assertArrayHasKey('timeout', $response['data']);
        $this->assertArrayHasKey('check_url', $response['data']);
    }

    public function testCheckTimeoutReturnsActiveWhenFresh()
    {
        session()->set('last_activity', time());
        $controller = new TestableSessionTimeoutController();
        $response = $controller->checkTimeout();

        $this->assertSame(ResponseInterface::HTTP_OK, $response['code']);
        $this->assertSame('Session active', $response['message']);
        $this->assertSame('active', $response['data']['status']);
    }

    public function testPingActivityRefreshesSession()
    {
        $controller = new TestableSessionTimeoutController();
        session()->set('last_activity', time());

        $response = $controller->pingActivity();
        $this->assertSame(ResponseInterface::HTTP_OK, $response['code']);
        $this->assertSame('Session activity refreshed', $response['message']);
        $this->assertSame('active', $response['data']['status']);
    }
}
