<?php

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

use App\Models\AdminUser;
use App\Models\Draw;
use App\Models\JackpotPool;
use App\Support\ApiResponse;
use App\Support\ApiMessage;
use App\Lottery\ErrorCode;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Services\Jackpot\JackpotManualBurstService;

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

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

        if (! $admin->isSuperAdmin()) {
            return ApiResponse::error(
                trans('admin.permission_denied', [], $request->lotteryLocale()),
                ErrorCode::AdminForbidden->value,
                ['required_any' => [AdminUser::ROLE_SUPER_ADMIN]],
                403,
            );
        }

        $data = $request->validate([
            'draw_id' => ['required'],
        ]);

        $drawId = $this->resolveDrawId(trim((string) $data['draw_id']));
        if ($drawId === null) {
            return ApiResponse::error(
                trans('validation.exists', ['attribute' => 'draw_id'], $request->lotteryLocale()),
                ErrorCode::ClientHttpError->value,
                ['draw_id' => [trans('validation.exists', ['attribute' => 'draw_id'], $request->lotteryLocale())]],
                422,
            );
        }

        try {
            $payload = $this->service->execute($pool, $drawId);
        } catch (\RuntimeException $e) {
            return ApiResponse::error(
                ApiMessage::get($request, 'jackpot_manual_burst_failed', [
                    'reason' => ApiMessage::reason($request, $e->getMessage()),
                ]),
                ErrorCode::ClientHttpError->value,
                ['reason' => $e->getMessage()],
                409,
            );
        }

        return ApiResponse::success($payload);
    }

    private function resolveDrawId(string $drawRef): ?int
    {
        if ($drawRef === '') {
            return null;
        }

        if (ctype_digit($drawRef)) {
            $draw = Draw::query()->whereKey((int) $drawRef)->first();
            if ($draw !== null) {
                return (int) $draw->id;
            }
        }

        $draw = Draw::query()->where('draw_no', $drawRef)->first();

        return $draw !== null ? (int) $draw->id : null;
    }
}
