from fastapi import APIRouter, HTTPException
from application.services.user_services import CreateUser, ViewUsers, ViewUserById
from infrastructure.adapters.persistence.user_repository_sql import SqlUserRepository
from application.exceptions import UserAlreadyExists

router = APIRouter()

@router.post("/")
def create_user(name:str, email:str, phone:str):
    service = CreateUser(SqlUserRepository())

    try:
        return service.execute(name,email,phone)
    except UserAlreadyExists as e:
        raise HTTPException (
            status_code=409,
            detail=str(e)
            )


@router.get("/")
def view_all_users():

    service = ViewUsers(SqlUserRepository())

    try:
        return service.execute()
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=e)

@router.get("/{id}")
def view_user_by_id(user_id: int):
    service = ViewUserById(SqlUserRepository())

    result = service.execute(user_id)

    if result is None:
        raise HTTPException(
            status_code=404,
            detail="User not found")

    return result