<?php

namespace App\Http\Controllers;

use App\Models\GameMatch;
use App\Services\MatchResultService;
use Illuminate\Http\Request;

class MatchController extends Controller
{
    public function __construct(private readonly MatchResultService $resultService) {}

    public function show(int $id)
    {
        $match = GameMatch::with(['host', 'guest', 'winner'])->findOrFail($id);

        if (in_array($match->status, ['pending', 'in_progress', 'submitted']) &&
            auth()->id() !== $match->host_id &&
            auth()->id() !== $match->guest_id &&
            ! auth()->user()?->can('access-admin')) {
            abort(403);
        }

        return view('match.show', compact('match'));
    }

    public function submit(Request $request, int $id)
    {
        $match = GameMatch::findOrFail($id);
        $user  = auth()->user();

        abort_unless($match->isParticipant($user), 403);
        abort_unless(in_array($match->status, ['pending', 'in_progress', 'submitted']), 422, 'Match is not active.');

        $validated = $request->validate([
            'score_host'  => ['required', 'integer', 'min:0', 'max:99'],
            'score_guest' => ['required', 'integer', 'min:0', 'max:99'],
        ]);

        $result = $this->resultService->submit(
            $match, $user, (int) $validated['score_host'], (int) $validated['score_guest']
        );

        $message = match ($result) {
            'finalized' => 'Match finalized! ELO updated.',
            'disputed'  => 'Scores differ — match sent to admin review.',
            default     => 'Score submitted. Waiting for opponent.',
        };

        return redirect()->route('match.show', $match->id)->with('success', $message);
    }

    public function history()
    {
        $user = auth()->user();

        $matches = GameMatch::with(['host', 'guest'])
            ->where(fn($q) => $q->where('host_id', $user->id)->orWhere('guest_id', $user->id))
            ->latest()
            ->paginate(20);

        return view('match.history', compact('matches'));
    }
}
