<?php

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

use App\Models\Draw;
use App\Models\AdminUser;
use App\Lottery\ErrorCode;
use App\Support\ApiResponse;
use App\Support\ApiMessage;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Services\Draw\DrawReopenService;
use App\Http\Requests\Admin\DrawReopenRequest;

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

    public function __invoke(DrawReopenRequest $request, Draw $draw): 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,
            );
        }

        try {
            $reopened = $this->service->reopenCooldownDraw($draw, $admin, $request->validated('reason') ?? null);
        } catch (\RuntimeException $e) {
            return ApiMessage::runtimeErrorResponse($request, $e);
        }

        return ApiResponse::success([
            'draw_no' => $reopened->draw_no,
            'status' => $reopened->status,
            'is_reopened' => (bool) $reopened->is_reopened,
            'current_result_version' => (int) $reopened->current_result_version,
            'cooling_end_time' => $reopened->cooling_end_time?->toIso8601String(),
        ]);
    }
}
