from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import JSONResponse

from app.core.response import error, ok
from app.db.session import get_db
from app.schemas.models import LoginRequest
from app.services import auth as auth_service
from sqlalchemy.orm import Session
from fastapi import Depends

router = APIRouter(prefix="/api/auth", tags=["Auth"])


@router.post("/login")
def login(body: LoginRequest, request: Request, db: Session = Depends(get_db)):
    try:
        user, token = auth_service.authenticate(db, body)
    except ValueError as exc:
        if str(exc) == "invalid_code":
            return JSONResponse(
                status_code=401,
                content=error(10002, "invalid_verification_code", request.state.request_id),
            )
        return JSONResponse(
            status_code=400,
            content=error(10003, str(exc), request.state.request_id),
        )

    return ok(
        {"token": token, "user": auth_service.user_to_dict(user)},
        request_id=request.state.request_id,
    )
