from fastapi import APIRouter, HTTPException, status

from app.application.runtime.assignment import RuntimeService
from app.schemas.runtime import (
    RuntimeAssignRequest,
    RuntimeAssignResponse,
    RuntimeBootstrapRequest,
    RuntimeBootstrapResponse,
    RuntimeEventRequest,
    RuntimeEventResponse,
    RuntimePayloadRequest,
    RuntimePayloadResponse,
)

router = APIRouter()
service = RuntimeService()


@router.post("/bootstrap", response_model=RuntimeBootstrapResponse)
async def runtime_bootstrap(
    request: RuntimeBootstrapRequest,
) -> RuntimeBootstrapResponse:
    return await service.bootstrap(request)


@router.post("/assign", response_model=RuntimeAssignResponse)
async def runtime_assign(request: RuntimeAssignRequest) -> RuntimeAssignResponse:
    item = await service.assign(request)
    if not item:
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            detail="No assignable variants were provided.",
        )
    return item


@router.post("/payload", response_model=RuntimePayloadResponse)
async def runtime_payload(request: RuntimePayloadRequest) -> RuntimePayloadResponse:
    return await service.payload(request)


@router.post("/events/impression", response_model=RuntimeEventResponse)
async def runtime_impression(request: RuntimeEventRequest) -> RuntimeEventResponse:
    return await service.ingest_event(request)


@router.post("/events/conversion", response_model=RuntimeEventResponse)
async def runtime_conversion(request: RuntimeEventRequest) -> RuntimeEventResponse:
    return await service.ingest_event(request)
