<?php

namespace Tests\Feature;

use App\Enums\MatchOutcome;
use App\Enums\MatchStatus;
use App\Models\Fixture;
use App\Models\Pick;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class QuinielaDomainTest extends TestCase
{
    use RefreshDatabase;

    public function test_user_pick_can_be_scored_against_a_match_result(): void
    {
        $user = User::factory()->create();

        $homeTeam = Team::create([
            'name' => 'Mexico',
            'short_name' => 'Mexico',
            'slug' => 'mexico',
            'fifa_code' => 'MEX',
        ]);

        $awayTeam = Team::create([
            'name' => 'Argentina',
            'short_name' => 'Argentina',
            'slug' => 'argentina',
            'fifa_code' => 'ARG',
        ]);

        $fixture = Fixture::create([
            'home_team_id' => $homeTeam->id,
            'away_team_id' => $awayTeam->id,
            'stage' => 'Group Stage',
            'venue' => 'Estadio Azteca',
            'starts_at' => now()->addDay(),
            'picks_lock_at' => now()->addHours(20),
            'status' => MatchStatus::Scheduled,
        ]);

        $this->assertTrue($fixture->isOpenForPicks());

        $pick = Pick::create([
            'user_id' => $user->id,
            'match_id' => $fixture->id,
            'selection' => MatchOutcome::Home,
            'submitted_at' => now(),
        ]);

        $fixture->update([
            'status' => MatchStatus::Finished,
            'home_score' => 2,
            'away_score' => 1,
            'result' => MatchOutcome::Home,
            'result_declared_at' => now()->addDay(),
        ]);

        $pick->update([
            'points_awarded' => 1,
            'graded_at' => now()->addDay(),
        ]);

        $pick->load('fixture');

        $this->assertTrue($pick->isCorrect());
        $this->assertSame(1, $user->picks()->sum('points_awarded'));
    }
}
