<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Security;
use App\Repositories\InstitutionRepository;
use App\Repositories\ReportRepository;
use App\Repositories\StatisticsRepository;
use App\Services\AiClient;

final class ApiController extends Controller
{
    public function map(): string
    {
        return $this->json(['reports' => (new ReportRepository())->latest(50)]);
    }

    public function statistics(): string
    {
        $statistics = new StatisticsRepository();

        return $this->json([
            'overview' => $statistics->overview(),
            'municipalities' => $statistics->byMunicipality(),
            'categories' => $statistics->byCategory(),
        ]);
    }

    public function institutions(): string
    {
        return $this->json(['institutions' => (new InstitutionRepository())->all()]);
    }

    public function assistant(): string
    {
        if ($response = $this->ensureCsrf()) {
            return $response;
        }

        if (!Security::rateLimit('assistant:' . ($_SERVER['REMOTE_ADDR'] ?? 'local'), 20, 60)) {
            return $this->json(['ok' => false, 'message' => 'AI асистентът е временно ограничен за този IP.'], 429);
        }

        $text = Security::cleanText((string) ($this->input()['message'] ?? ''), 4000);
        $result = (new AiClient())->improveReport($text);

        return $this->json(['ok' => true, 'result' => $result]);
    }
}
