<?php

namespace App\Http\Controllers\Api\V1\Ticket;

use App\Support\ApiResponse;
use App\Support\LotteryMessage;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Exceptions\TicketOperationException;
use App\Services\Ticket\TicketPreviewService;
use App\Http\Requests\Ticket\TicketPreviewRequest;

final class TicketPreviewController extends Controller
{
    public function __construct(
        private readonly TicketPreviewService $previewService,
    ) {}

    public function __invoke(TicketPreviewRequest $request): JsonResponse
    {
        $player = $request->lotteryPlayer();
        abort_if($player === null, 500, 'lottery_player missing');

        try {
            $data = $this->previewService->preview($player, $request->validated());
        } catch (TicketOperationException $e) {
            return ApiResponse::error(
                LotteryMessage::wallet($request, $e->lotteryCode),
                $e->lotteryCode,
                $e->payload,
                $e->httpStatus,
            );
        }

        return ApiResponse::success($data);
    }
}
