<?php

namespace Tests\App\Controllers\Api;

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

class ScorePredictorStubBuilder
{
    private string $name;

    public function __construct(string $name)
    {
        $this->name = $name;
    }

    public function select(...$args)
    {
        return $this;
    }

    public function join(...$args)
    {
        return $this;
    }

    public function where(...$args)
    {
        return $this;
    }

    public function groupBy(...$args)
    {
        return $this;
    }

    public function get()
    {
        return $this;
    }

    public function getResultArray(): array
    {
        return [];
    }

    public function getRow(): object
    {
        return (object)['mean' => 70, 'std' => 10];
    }
}

class ScorePredictorStubDatabase
{
    public function connect()
    {
        return true;
    }

    public function escape($value)
    {
        return "'" . addslashes((string)$value) . "'";
    }

    public function table(string $name)
    {
        return new ScorePredictorStubBuilder($name);
    }
}

class StubConfigurationModel
{
    public function getConfig($key)
    {
        return match ($key) {
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'trophy_score' => 95,
            'pass_score' => 60,
            default => null,
        };
    }
}

class StubClassSectionModel
{
    public function findAll(): array
    {
        return [];
    }
}

class TestableScorePredictor extends ScorePredictor
{
    public function __construct()
    {
        $this->db = new ScorePredictorStubDatabase();
        $this->configModel = new StubConfigurationModel();
        $this->classSectionModel = new StubClassSectionModel();
        $this->semester = 'Fall';
        $this->schoolYear = '2025-2026';
        $this->targetTrophy = 95;
        $this->targetLow = 60;
    }

    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 ScorePredictorTest extends CIUnitTestCase
{
    public function testCombinedReportReturnsSuccess()
    {
        $controller = new TestableScorePredictor();
        $response = $controller->combinedReport();

        $this->assertSame(ResponseInterface::HTTP_OK, $response['code']);
        $this->assertArrayHasKey('students', $response['data']);
        $this->assertArrayHasKey('class_sections', $response['data']);
        $this->assertSame('Score prediction generated', $response['message']);
    }
}
