<?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');

        // Cache/throttler keys cannot contain reserved characters.
        // Raw IPv6 addresses contain ":", so hash the IP first.
        $ip = $this->request->getIPAddress();
        $key = 'proofread-' . hash('sha256', $ip);

        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
        $payload = sanitize_request_value($this->request->getPost(['text']));

        $validation = service('validation');
        $validation->setRules([
            'text' => 'required|min_length[1]|max_length[20000]',
        ]);

        if (! $validation->run($payload)) {
            return $this->respond([
                'ok' => false,
                'error' => 'Invalid text payload.',
                'csrfHash' => csrf_hash(),
            ], 422);
        }

        $text = (string) $payload['text'];

        $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',
                ],
            ]);

            $result = json_decode($resp->getBody(), true);

            if (json_last_error() !== JSON_ERROR_NONE) {
                return $this->respond([
                    'ok' => false,
                    'error' => 'Invalid response from proofread service.',
                    'csrfHash' => csrf_hash(),
                ], 502);
            }

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