<?php

namespace App\Http\Controllers;

use App\Services\MatchmakingService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

class MatchmakingController extends Controller
{
    public function __construct(private readonly MatchmakingService $service) {}

    public function index()
    {
        return view('matchmaking.index');
    }

    /**
     * POST /api/matchmaking/join
     */
    public function join(): JsonResponse
    {
        $user  = auth()->user();
        $entry = DB::transaction(fn() => $this->service->joinQueue($user));

        // Immediately try to find a match
        $match = DB::transaction(fn() => $this->service->tryMatch($entry->fresh()));

        return response()->json([
            'queued'   => true,
            'matched'  => (bool) $match,
            'match_id' => $match?->id,
        ]);
    }

    /**
     * POST /api/matchmaking/leave
     */
    public function leave(): JsonResponse
    {
        $this->service->leaveQueue(auth()->user());
        return response()->json(['left' => true]);
    }

    /**
     * GET /api/matchmaking/status
     */
    public function status(): JsonResponse
    {
        return response()->json(
            $this->service->getStatus(auth()->user())
        );
    }
}
