<?php

namespace Tests\Feature\Api\V1\Utilities;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

class ProofreadControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_proofread_requires_authentication(): void
    {
        $this->postJson('/api/proofread', ['text' => 'hello'])
            ->assertStatus(401);
    }

    public function test_proofread_rejects_empty_text(): void
    {
        Sanctum::actingAs(User::factory()->create());

        $this->postJson('/api/proofread', ['text' => ''])
            ->assertStatus(422)
            ->assertJsonPath('ok', false);
    }

    public function test_proofread_rejects_text_that_is_too_long(): void
    {
        Sanctum::actingAs(User::factory()->create());

        $this->postJson('/api/proofread', ['text' => str_repeat('a', 20001)])
            ->assertStatus(422)
            ->assertJsonPath('ok', false);
    }

    public function test_proofread_proxies_languagetool_and_returns_result(): void
    {
        Http::fake([
            'api.languagetool.org/*' => Http::response(['matches' => []], 200),
        ]);

        Sanctum::actingAs(User::factory()->create());

        $this->postJson('/api/proofread', ['text' => 'This are a test.'])
            ->assertOk()
            ->assertJsonPath('ok', true)
            ->assertJsonStructure(['ok', 'result', 'csrfHash']);

        Http::assertSent(fn ($request) => str_contains($request->url(), 'languagetool.org'));
    }

    public function test_proofread_returns_502_when_upstream_fails(): void
    {
        Http::fake([
            'api.languagetool.org/*' => Http::response('error', 500),
        ]);

        Sanctum::actingAs(User::factory()->create());

        $this->postJson('/api/proofread', ['text' => 'Some text to check.'])
            ->assertStatus(502)
            ->assertJsonPath('ok', false);
    }
}
