from typing import Annotated, Any
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from backend.core.config import get_app_settings
from backend.core.dependencies import is_logged_in
from backend.core.message_code import MessageCode
from backend.db.db_setup import generate_session
from backend.schemas.common import ReturnValue
from backend.schemas.user import ProfileResponse, UserCreate, UserProfile
from backend.services.user import UserService


public_router = APIRouter(tags=["Users: Info"])
user_service = UserService()
settings = get_app_settings()

db_dependency = Annotated[Session, Depends(generate_session)]
current_user_token = Annotated[ProfileResponse, Depends(is_logged_in)]

@public_router.put('/register')
def register_user(user: UserCreate, db: db_dependency) -> ReturnValue[Any]:
  db_user = user_service.get_by_username(username=user.username)
  if db_user:
    raise HTTPException(status_code=400, detail=MessageCode.CREATED_USER)
  user_service.create(db=db, user=user)
  return ReturnValue(status=200, data="created")

@public_router.get("/me", response_model=ReturnValue[ProfileResponse])
def get_user(current_user: current_user_token) -> ReturnValue[Any]:
  return ReturnValue(status=200, data=current_user)

@public_router.put("/update-profile", response_model=ReturnValue[ProfileResponse])
def update_user(user: UserProfile, current_user: current_user_token, db: db_dependency) -> ReturnValue[Any]:
  db_user = user_service.update(db=db, user=user, user_id=current_user.id)
  return ReturnValue(status=200, data=db_user)
