<?php

namespace Tests\Feature;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;

/**
 * Système de tickets utilisateur : le formulaire de suggestions crée une
 * issue dans Gitea via son API.
 */
class SuggestionTest extends TestCase
{
    use RefreshDatabase;

    #[Test]
    public function un_invite_est_redirige_vers_login()
    {
        $this->get('/suggestions/nouveau')->assertRedirect('/login');
    }

    #[Test]
    public function un_utilisateur_connecte_voit_le_formulaire()
    {
        $this->actingAs(User::factory()->create())
            ->get('/suggestions/nouveau')
            ->assertOk()
            ->assertSee('Signaler');
    }

    #[Test]
    public function une_demande_valide_cree_un_ticket_gitea()
    {
        config([
            'services.gitea.url' => 'https://gitea.test',
            'services.gitea.token' => 'fake-token',
            'services.gitea.repo' => 'sam/cesizen',
        ]);
        Http::fake(['*' => Http::response(['number' => 1], 201)]);

        $this->actingAs(User::factory()->create())
            ->post('/suggestions', [
                'type' => 'Correction',
                'titre' => 'Un bug sur la page',
                'description' => 'Description suffisamment longue du problème rencontré.',
            ])
            ->assertRedirect(route('suggestions.create'))
            ->assertSessionHas('success');

        Http::assertSent(fn ($request) => str_contains($request->url(), '/api/v1/repos/sam/cesizen/issues'));
    }

    #[Test]
    public function une_demande_invalide_est_rejetee()
    {
        $this->actingAs(User::factory()->create())
            ->post('/suggestions', ['type' => 'Invalide', 'titre' => 'a', 'description' => 'b'])
            ->assertSessionHasErrors(['type', 'titre', 'description']);
    }
}
