from uuid import UUID

from fastapi import APIRouter, Depends

from app.api.deps import AsyncSession, CurrentUser, get_db, require_tenant
from app.api.permissions import require_permissions
from app.permissions.definitions import OTP_REQUEST, OTP_VERIFY
from app.schemas.common import OTPRequest, OTPRequestOut, OTPVerifyOut, OTPVerifyRequest
from app.services.otp_service import OTPService

router = APIRouter()


@router.post("/request", response_model=OTPRequestOut, status_code=201)
async def request_otp(
    body: OTPRequest,
    tenant_id: UUID = Depends(require_tenant),
    session: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(OTP_REQUEST)),
):
    challenge, debug_code = await OTPService(session).request(
        tenant_id, body.model_dump(), actor_id=user.user_id
    )
    return OTPRequestOut(
        challenge_id=challenge.id,
        destination=challenge.destination,
        channel=challenge.channel,
        expires_at=challenge.expires_at,
        message_id=challenge.message_id,
        debug_code=debug_code,
    )


@router.post("/verify", response_model=OTPVerifyOut)
async def verify_otp(
    body: OTPVerifyRequest,
    tenant_id: UUID = Depends(require_tenant),
    session: AsyncSession = Depends(get_db),
    _: CurrentUser = Depends(require_permissions(OTP_VERIFY)),
):
    result = await OTPService(session).verify(tenant_id, body.model_dump())
    return OTPVerifyOut(**result)
