<?php

namespace App\Http\Controllers\Api\Utilities;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\RateLimiter;

/**
 * legacy {@see \App\Controllers\ProofreadController} — LanguageTool proxy for grading UI.
 */
class ProofreadController extends Controller
{
    public function check(Request $request): JsonResponse
    {
        $key = 'proofread-'.$request->ip();
        if (RateLimiter::tooManyAttempts($key, 10)) {
            return response()->json([
                'ok' => false,
                'error' => 'Too many requests. Try again in a minute.',
                'csrfHash' => csrf_token(),
            ], 429);
        }

        RateLimiter::hit($key, 60);

        $text = (string) ($request->input('text') ?? '');
        if ($text === '' || mb_strlen($text) > 20000) {
            return response()->json([
                'ok' => false,
                'error' => 'Invalid text (empty or too long).',
                'csrfHash' => csrf_token(),
            ], 422);
        }

        try {
            $resp = Http::timeout(10)
                ->asForm()
                ->post('https://api.languagetool.org/v2/check', [
                    'text' => $text,
                    'language' => 'en-US',
                ]);

            if (! $resp->successful()) {
                return response()->json([
                    'ok' => false,
                    'error' => 'Proofread service unavailable.',
                    'csrfHash' => csrf_token(),
                ], 502);
            }

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