<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\CompetitionAssignment;
use App\Models\MatchContest;
use App\Services\StudentExamService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class StudentResultController extends Controller
{
    public function __construct(
        private readonly StudentExamService $examService,
    ) {
    }

    public function index(Request $request): JsonResponse
    {
        return response()->json(
            $this->examService->buildPublishedResultsPayload($request->user())
        );
    }

    public function show(Request $request, MatchContest $contest): JsonResponse
    {
        $preferredAssignmentId = $request->integer('assignment_id');

        $result = $this->examService->buildCompetitionResultPayload(
            $request->user(),
            $contest,
            $preferredAssignmentId > 0 ? $preferredAssignmentId : null,
        );

        $statusCode = match ($result['status'] ?? 'missing') {
            'ok' => 200,
            'locked' => 403,
            'missing' => 404,
            default => 422,
        };

        return response()->json($result, $statusCode);
    }

    public function answerSheet(Request $request, CompetitionAssignment $assignment): JsonResponse
    {
        $result = $this->examService->buildAnswerSheetPayload($request->user(), $assignment);

        $statusCode = match ($result['status'] ?? 'missing') {
            'ok' => 200,
            'locked' => 403,
            'missing' => 404,
            default => 422,
        };

        return response()->json($result, $statusCode);
    }
}
