<?php

namespace Tests\Feature\Api\V1\Public;

use App\Models\Competition;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class PublicWinnersControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_competition_index_is_public_and_returns_published_competitions(): void
    {
        Competition::query()->create([
            'title' => 'Published Quiz Bowl',
            'school_year' => '2025-2026',
            'is_published' => 1,
            'published_at' => now(),
        ]);

        Competition::query()->create([
            'title' => 'Hidden Draft',
            'school_year' => '2025-2026',
            'is_published' => 0,
        ]);

        $response = $this->getJson('/api/winners/competitions');

        $response->assertOk()
            ->assertJsonPath('status', true)
            ->assertJsonStructure(['status', 'data' => ['competitions']]);

        $titles = array_column($response->json('data.competitions'), 'title');
        $this->assertContains('Published Quiz Bowl', $titles);
        $this->assertNotContains('Hidden Draft', $titles);
    }

    public function test_competition_index_returns_empty_collection_when_none_published(): void
    {
        $this->getJson('/api/winners/competitions')
            ->assertOk()
            ->assertJsonPath('status', true)
            ->assertJsonPath('data.competitions', []);
    }

    public function test_competition_show_returns_payload_for_published_competition(): void
    {
        $competition = Competition::query()->create([
            'title' => 'Spelling Bee',
            'school_year' => '2025-2026',
            'is_published' => 1,
            'published_at' => now(),
        ]);

        $this->getJson('/api/winners/competitions/' . $competition->id)
            ->assertOk()
            ->assertJsonPath('status', true)
            ->assertJsonPath('data.competition.id', $competition->id)
            ->assertJsonStructure(['data' => ['competition', 'winners_by_class', 'section_map', 'question_counts']]);
    }

    public function test_competition_show_returns_404_for_unknown_competition(): void
    {
        $this->getJson('/api/winners/competitions/999999')
            ->assertNotFound()
            ->assertJsonPath('status', false);
    }

    public function test_competition_show_returns_404_for_unpublished_competition(): void
    {
        $competition = Competition::query()->create([
            'title' => 'Unpublished',
            'school_year' => '2025-2026',
            'is_published' => 0,
        ]);

        $this->getJson('/api/winners/competitions/' . $competition->id)
            ->assertNotFound()
            ->assertJsonPath('status', false);
    }
}
