<?php

namespace Tests\App\Filters;

use App\Filters\SanitizeInputFilter;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\Response;
use CodeIgniter\HTTP\URI;
use CodeIgniter\HTTP\UserAgent;
use CodeIgniter\Test\CIUnitTestCase;
use Config\App;
use Config\Services;

class SanitizeInputFilterTest extends CIUnitTestCase
{
    public function testSanitizesGetPostAndJsonPayloads(): void
    {
        $request = new IncomingRequest(config(App::class), new URI('https://example.test/api/login'), 'php://input', new UserAgent());
        $request->setHeader('Content-Type', 'application/json');
        $request->setGlobal('get', ['q' => "  hello\x00  "]);
        $request->setGlobal('post', ['email' => " user@example.com \n"]);
        $request->setGlobal('request', ['email' => " user@example.com \n"]);
        $request->setGlobal('cookie', ['token' => " abc\t"]);
        $request->setBody("{\"email\":\" user@example.com \",\"name\":\" Bob\\u0000 \"}");

        $filter = new SanitizeInputFilter();
        $result = $filter->before($request);

        $this->assertNull($result);
        $this->assertSame('hello', $request->getGet('q'));
        $this->assertSame('user@example.com', $request->getPost('email'));
        $this->assertSame('abc', $request->getCookie('token'));
        $this->assertSame(['email' => 'user@example.com', 'name' => 'Bob'], $request->getJSON(true));
    }

    public function testRejectsMalformedJsonPayload(): void
    {
        $request = new IncomingRequest(config(App::class), new URI('https://example.test/api/login'), 'php://input', new UserAgent());
        $request->setHeader('Content-Type', 'application/json');
        $request->setBody('{invalid');

        $filter = new SanitizeInputFilter();
        $result = $filter->before($request);

        $this->assertInstanceOf(Response::class, $result);
        $this->assertSame(400, $result->getStatusCode());
    }
}
