<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Prediction\StorePredictionRequest;
use App\Http\Resources\PredictionResource;
use App\Interfaces\PredictionRepositoryInterface;
use App\Services\PredictionService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class PredictionController extends Controller
{
    public function __construct(
        private readonly PredictionService $predictionService,
        private readonly PredictionRepositoryInterface $predictionRepository
    ) {}

    public function store(StorePredictionRequest $request): JsonResponse
    {
        $result = $this->predictionService->submitPrediction(
            $request->user(),
            $request->match_id,
            $request->prediction
        );

        return response()->json([
            'message'    => 'Prediction saved!',
            'prediction' => new PredictionResource($result['prediction']),
        ], 201);
    }

    public function myPredictions(Request $request): JsonResponse
    {
        $predictions = $this->predictionRepository->getUserPredictions($request->user()->id);

        return response()->json([
            'predictions' => PredictionResource::collection($predictions),
        ]);
    }

    public function matchPrediction(Request $request, int $matchId): JsonResponse
    {
        $prediction = $this->predictionRepository->findByUserAndMatch(
            $request->user()->id,
            $matchId
        );

        if (! $prediction) {
            return response()->json(['prediction' => null]);
        }

        return response()->json([
            'prediction' => new PredictionResource($prediction),
        ]);
    }
}
