<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
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:id,username,avatar,elo', 'guest:id,username,avatar,elo', 'winner:id,username'])
            ->findOrFail($id);

        abort_unless($match->isParticipant(auth()->user()) || auth()->user()->can('access-admin'), 403);

        return response()->json($match);
    }

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

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

        return response()->json($matches);
    }

    public function submitResult(Request $request)
    {
        $validated = $request->validate([
            'match_id'    => ['required', 'integer', 'exists:matches,id'],
            'score_host'  => ['required', 'integer', 'min:0', 'max:99'],
            'score_guest' => ['required', 'integer', 'min:0', 'max:99'],
        ]);

        $match = GameMatch::findOrFail($validated['match_id']);
        $user  = auth()->user();

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

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

        return response()->json(['result' => $result]);
    }
}
