import {
  type CreateUserDto,
  type UserDto,
  ResponseError
} from '~/.api-client'
import { useUserApi } from './useUserApi'

export function useUser() {
  const userApi = useUserApi()

  async function createUser(createUserDto: CreateUserDto): Promise<UserDto> {
    try {
      return await userApi.createUser(createUserDto)
    } catch (e: unknown) {
      if (e instanceof ResponseError) {
        console.error('Failed creating user:', e.response)
      } else {
        console.error('Failed creating user:', e)
      }
      return Promise.reject(e)
    }
  }

  async function getUserById(id: string): Promise<UserDto | null> {
    try {
      return await userApi.getUserById(id)
    } catch (e: unknown) {
      if (e instanceof ResponseError && e.response.status === 404) {
        return null
      }
      if (e instanceof ResponseError) {
        console.error(`Failed retrieving user with ID ${id}:`, e.response)
      } else {
        console.error(`Failed retrieving user with ID ${id}:`, e)
      }
      return Promise.reject(e)
    }
  }

  async function updateUser(id: string, userDto?: UserDto): Promise<UserDto> {
    try {
      return await userApi.updateUser(id, userDto)
    } catch (e: unknown) {
      if (e instanceof ResponseError) {
        console.error(`Failed updating user with ID ${id}:`, e.response)
      } else {
        console.error(`Failed updating user with ID ${id}:`, e)
      }
      return Promise.reject(e)
    }
  }

  async function deleteUser(id: string): Promise<void> {
    try {
      return await userApi.deleteUser(id)
    } catch (e: unknown) {
      if (e instanceof ResponseError) {
        console.error(`Failed deleting user with ID ${id}:`, e.response)
      } else {
        console.error(`Failed deleting user with ID ${id}:`, e)
      }
      return Promise.reject(e)
    }
  }

  return {
    createUser,
    getUserById,
    updateUser,
    deleteUser
  }
} 