from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException, status

from backend.app.api.deps import get_current_user
from backend.app.models import AuthResponse, LoginRequest, RegisterRequest, UserPublic
from backend.app.services.auth import (
    authenticate_user,
    issue_token_for_user,
    register_user,
)

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


@router.post("/login", response_model=AuthResponse)
async def login(credentials: LoginRequest) -> AuthResponse:
    user = authenticate_user(credentials.username, credentials.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return issue_token_for_user(user)


@router.post(
    "/register", response_model=AuthResponse, status_code=status.HTTP_201_CREATED
)
async def register(payload: RegisterRequest) -> AuthResponse:
    try:
        user = register_user(payload.username, payload.password, payload.full_name)
    except ValueError as exc:
        message = str(exc)
        status_code = (
            status.HTTP_409_CONFLICT
            if "exists" in message
            else status.HTTP_400_BAD_REQUEST
        )
        raise HTTPException(status_code=status_code, detail=message) from exc
    return issue_token_for_user(user)


@router.get("/me", response_model=UserPublic)
async def read_current_user(
    current_user: UserPublic = Depends(get_current_user),
) -> UserPublic:
    return current_user
