<?php

namespace App\Http\Controllers\Api\V1\Admin\Settlement;

use App\Models\AdminUser;
use App\Support\ApiMessage;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;
use App\Models\SettlementBatch;
use App\Http\Controllers\Controller;
use App\Support\LotteryMessage;
use App\Exceptions\TicketOperationException;
use App\Services\Settlement\SettlementPayoutCorrectionService;
use App\Http\Requests\Admin\SettlementPayoutAdjustmentRequest;

final class AdminSettlementBatchAdjustmentController extends Controller
{
    public function __construct(
        private readonly SettlementPayoutCorrectionService $service,
    ) {}

    public function __invoke(SettlementPayoutAdjustmentRequest $request, SettlementBatch $batch): JsonResponse
    {
        $admin = $request->user();
        if (! $admin instanceof AdminUser) {
            return ApiResponse::error(
                trans('admin.unauthenticated', [], $request->lotteryLocale()),
                \App\Lottery\ErrorCode::AdminUnauthenticated->value,
                null,
                401,
            );
        }

        try {
            $result = $this->service->apply(
                $batch,
                $admin,
                (int) $request->validated('player_id'),
                (int) $request->validated('amount_delta'),
                (string) $request->validated('reason'),
                $request,
            );
        } catch (TicketOperationException $e) {
            return ApiResponse::error(
                LotteryMessage::wallet($request, $e->lotteryCode),
                $e->lotteryCode,
                $e->payload,
                $e->httpStatus,
            );
        } catch (\RuntimeException $e) {
            return ApiMessage::runtimeErrorResponse($request, $e, 0, 422);
        }

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