<?php

namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;

class ProofreadController extends ResourceController
{
    public function check()
    {
        // Basic per-IP throttling: 10 requests per minute
        $throttler = service('throttler');
        $key = 'proofread-' . $this->request->getIPAddress();
        if (!$throttler->check($key, 10, MINUTE)) {
            return $this->respond([
                'ok' => false,
                'error' => 'Too many requests. Try again in a minute.',
                'csrfHash' => csrf_hash(),
            ], 429);
        }

        // Accept form-urlencoded payload to play nicely with CSRF protection
        $text = (string) ($this->request->getPost('text') ?? '');
        if ($text === '' || mb_strlen($text) > 20000) {
            return $this->respond([
                'ok' => false,
                'error' => 'Invalid text (empty or too long).',
                'csrfHash' => csrf_hash(),
            ], 422);
        }

        $client = \Config\Services::curlrequest(['timeout' => 10]);

        try {
            $resp = $client->post('https://api.languagetool.org/v2/check', [
                'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],
                'form_params' => [
                    'text'     => $text,
                    'language' => 'en-US',
                ],
            ]);

            return $this->respond([
                'ok' => true,
                'result' => json_decode($resp->getBody(), true),
                'csrfHash' => csrf_hash(),
            ]);
        } catch (\Throwable $e) {
            return $this->respond([
                'ok' => false,
                'error' => 'Proofread service unavailable.',
                'csrfHash' => csrf_hash(),
            ], 502);
        }
    }
}
