<?php

namespace Tests\App\Controllers\Api;

use App\Controllers\Api\HealthController;
use CodeIgniter\Test\CIUnitTestCase;
use Config\Services;
use CodeIgniter\HTTP\IncomingRequest;

class StubHealthController extends HealthController
{
    private $dbConnection;

    public function setDatabaseConnection($connection): void
    {
        $this->dbConnection = $connection;
    }

    protected function getDatabaseConnection()
    {
        return $this->dbConnection ?? parent::getDatabaseConnection();
    }

    protected function respond($data = null, ?int $status = null, string $message = '')
    {
        $payload = is_array($data) ? $data : [];
        $payload['code'] = $status;
        return $payload;
    }
}

class StubDbConnection
{
    public function __construct(
        private array $tables = [],
        private array $fields = []
    ) {
    }

    public function tableExists(string $table): bool
    {
        return $this->tables[$table] ?? true;
    }

    public function fieldExists(string $field, string $table): bool
    {
        return $this->fields[$table][$field] ?? true;
    }
}

class HealthControllerTest extends CIUnitTestCase
{
    private StubHealthController $controller;

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

        $this->controller = new StubHealthController();
        $request = $this->createMock(IncomingRequest::class);
        $this->controller->setRequest($request);
        $response = Services::response();
        self::setPrivateProperty($this->controller, 'response', $response);
    }

    public function testIndexReportsOkWhenAllChecksPass()
    {
        $stubDb = new StubDbConnection(
            ['user_preferences' => true, 'settings' => true, 'migrations' => true],
            [
                'user_preferences' => ['timezone' => true],
                'settings' => ['timezone' => true],
            ]
        );
        $this->controller->setDatabaseConnection($stubDb);

        $result = $this->controller->index();

        $this->assertArrayHasKey('ok', $result);
        $this->assertTrue($result['ok']);
        $this->assertSame(WRITEPATH, $result['write_path']);
        $this->assertSame(200, $result['code']);
        $this->assertSame(true, $result['database']['user_preferences_exists']);
    }

    public function testIndexReturns503WhenFieldMissing()
    {
        $stubDb = new StubDbConnection(
            ['user_preferences' => true, 'settings' => true, 'migrations' => true],
            [
                'user_preferences' => ['timezone' => false],
                'settings' => ['timezone' => true],
            ]
        );
        $this->controller->setDatabaseConnection($stubDb);

        $result = $this->controller->index();

        $this->assertArrayHasKey('ok', $result);
        $this->assertFalse($result['ok']);
        $this->assertSame(503, $result['code']);
        $this->assertFalse($result['database']['user_preferences_has_timezone']);
    }
}
