<?php

namespace Tests\App\Controllers\Api;

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

class StubQuery
{
    public function getRow()
    {
        return (object)['result' => 1];
    }
}

class StubDatabase
{
    public function query(string $sql)
    {
        return new StubQuery();
    }
}

class TestableTestDBController extends TestDBController
{
    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];
    }

    protected function getDatabaseConnection()
    {
        return new StubDatabase();
    }
}

class TestDBControllerTest extends CIUnitTestCase
{
    public function testIndexReturnsSuccessWhenDatabaseOk()
    {
        $controller = new TestableTestDBController();
        $response = $controller->index();

        $this->assertSame(ResponseInterface::HTTP_OK, $response['code']);
        $this->assertSame('Database check completed', $response['message']);
        $this->assertSame('Database connection is successful.', $response['data']['message']);
    }
}
