<?php

namespace Tests\Feature\Audit;

use CodeIgniter\Test\FeatureTestTrait;
use CodeIgniter\Test\CIUnitTestCase;
use Firebase\JWT\JWT;

class AuditLogTest extends CIUnitTestCase
{
    use FeatureTestTrait;

    protected $db;
    private $testRecId = 'TEST-REC-123';

    protected function setUp(): void
    {
        parent::setUp();

        $this->db = \Config\Database::connect();
        $this->db->table('logpatient')->insert([
            'TblName' => 'patient',
            'RecID' => $this->testRecId,
            'UserID' => 'USR_TEST',
            'SiteID' => 'SITE01',
            'SessionID' => 'sess_test',
            'AppID' => 'clqms-api',
            'EventID' => 'PATIENT_REGISTERED',
            'ActivityID' => 'CREATE',
            'LogDate' => '2026-03-25 12:00:00',
            'Context' => json_encode([
                'request_id' => 'req-test-1',
                'route' => 'POST /api/patient',
                'timestamp_utc' => '2026-03-25T12:00:00.000Z',
                'entity_type' => 'patient',
                'entity_version' => 1,
            ]),
        ]);
    }

    protected function tearDown(): void
    {
        $this->db->table('logpatient')->where('RecID', $this->testRecId)->delete();
        parent::tearDown();
    }

    public function testTableIsRequired()
    {
        $result = $this->getWithAuth('api/audit-logs');

        $result->assertStatus(400);
        $result->assertJSONFragment([
            'status' => 'failed',
            'message' => 'table parameter is required',
        ]);
    }

    public function testUnknownTableReturnsValidationError()
    {
        $result = $this->getWithAuth('api/audit-logs?table=unknown');

        $result->assertStatus(400);
        $result->assertJSONFragment([
            'status' => 'failed',
            'message' => 'Unknown audit table: unknown',
        ]);
    }

    public function testAuditLogsFilterByRecId()
    {
        $result = $this->getWithAuth('api/audit-logs?table=logpatient&rec_id=' . $this->testRecId);

        $result->assertStatus(200);
        $result->assertJSONFragment([
            'status' => 'success',
        ]);

        $payload = json_decode($result->getJSON(), true);
        $this->assertCount(1, $payload['data']['data']);
        $this->assertEquals($this->testRecId, $payload['data']['data'][0]['RecID']);

        $pagination = $payload['data']['pagination'];
        $this->assertSame(1, $pagination['page']);
        $this->assertSame(20, $pagination['perPage']);
        $this->assertSame(1, $pagination['total']);
    }

    private function getWithAuth(string $uri)
    {
        $_COOKIE['token'] = $this->buildToken();

        $response = $this->get($uri);

        unset($_COOKIE['token']);

        return $response;
    }

    private function buildToken(): string
    {
        $payload = [
            'sub' => 'audit-test',
            'iat' => time(),
        ];

        return JWT::encode($payload, $this->resolveSecret(), 'HS256');
    }

    private function resolveSecret(): string
    {
        $secret = getenv('JWT_SECRET');
        if ($secret === false) {
            return 'tests-secret';
        }
        return trim($secret, "'\"");
    }
}
