<?php
namespace Tests\Feature\Candidat;

use App\Models\Candidat;
use App\Models\User;
use App\Models\Ville;
use App\Models\Quartier;
use App\Enums\StatutCompteUser;
use App\Enums\StatutCandidat;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class DossierTest extends TestCase
{
    use RefreshDatabase;

    private User $candidatUser;
    private Candidat $candidat;

    protected function setUp(): void
    {
        parent::setUp();
        $ville = Ville::factory()->active()->create();
        $this->candidatUser = User::factory()->candidat()->create(['statut' => StatutCompteUser::ACTIF]);
        $this->candidat = Candidat::factory()->create([
            'user_id'  => $this->candidatUser->id,
            'ville_id' => $ville->id,
            'statut'   => StatutCandidat::SOUMIS->value,
        ]);
    }

    public function test_candidat_peut_voir_son_dossier(): void
    {
        $response = $this->actingAs($this->candidatUser)
            ->getJson('/api/candidat/dossier');

        $response->assertStatus(200)
            ->assertJsonStructure([
                'dossier' => [
                    'id', 'reference', 'nom', 'prenom', 'statut',
                    'dossier_complet', 'pieces_jointes', 'parrain'
                ]
            ]);
    }

    public function test_candidat_peut_mettre_a_jour_son_profil(): void
    {
        $response = $this->actingAs($this->candidatUser)
            ->putJson('/api/candidat/dossier', [
                'nom'    => 'Nguema',
                'prenom' => 'Marie',
            ]);

        $response->assertStatus(200)
            ->assertJsonPath('dossier.nom', 'Nguema');

        $this->assertDatabaseHas('candidats', ['nom' => 'Nguema']);
    }

    public function test_candidat_ne_peut_pas_modifier_son_statut(): void
    {
        $response = $this->actingAs($this->candidatUser)
            ->putJson('/api/candidat/dossier', [
                'statut' => StatutCandidat::DISPONIBLE->value,
            ]);

        // Le statut ne doit pas avoir changé
        $this->assertDatabaseHas('candidats', [
            'id'     => $this->candidat->id,
            'statut' => StatutCandidat::SOUMIS->value,
        ]);
    }

    public function test_candidat_peut_voir_historique_statut(): void
    {
        $response = $this->actingAs($this->candidatUser)
            ->getJson('/api/candidat/dossier/statut');

        $response->assertStatus(200)
            ->assertJsonStructure(['statut_actuel' => ['valeur', 'label'], 'historique']);
    }

    public function test_visiteur_non_connecte_ne_peut_pas_voir_dossier(): void
    {
        $this->getJson('/api/candidat/dossier')->assertStatus(401);
    }

    public function test_client_ne_peut_pas_acceder_espace_candidat(): void
    {
        $client = User::factory()->create(['role' => 'client', 'statut' => StatutCompteUser::ACTIF]);
        $this->actingAs($client)->getJson('/api/candidat/dossier')->assertStatus(403);
    }
}
