import {
  NotificationApi,
  Configuration,
  type NotificationDto,
  type PagedNotificationDto,
  type CreateNotificationDto
} from '~/.api-client'
import { cleanDoubleSlashes, withoutTrailingSlash } from 'ufo'

export function useNotificationApi() {
  const appBaseUrl = useRuntimeConfig().app.baseURL
  const { serverApiBaseUrl, serverApiBasePath, clientProxyBasePath } = useRuntimeConfig().public
  const { jwt } = useAuth()

  const basePath = withoutTrailingSlash(
    cleanDoubleSlashes(import.meta.client ? appBaseUrl + clientProxyBasePath : serverApiBaseUrl + serverApiBasePath)
  )

  const notificationApiClient = new NotificationApi(
    new Configuration({ basePath, headers: { Authorization: jwt.value ? `Bearer ${jwt.value}` : '' } })
  )

  async function createNotification(createNotificationDto: CreateNotificationDto): Promise<NotificationDto> {
    return notificationApiClient.createNotification({ createNotificationDto })
  }

  async function getNotifications(page?: number, size?: number): Promise<PagedNotificationDto> {
    return notificationApiClient.getNotifications({ page, size })
  }

  async function getUnreadNotifications(): Promise<NotificationDto[]> {
    return notificationApiClient.getUnreadNotifications()
  }

  async function getUnreadNotificationCount(): Promise<number> {
    return notificationApiClient.getUnreadNotificationCount()
  }

  async function markAllNotificationsAsRead(): Promise<void> {
    return notificationApiClient.markAllNotificationsAsRead()
  }

  async function markNotificationAsRead(id: string): Promise<NotificationDto> {
    return notificationApiClient.markNotificationAsRead({ id })
  }

  return {
    createNotification,
    getNotifications,
    getUnreadNotifications,
    getUnreadNotificationCount,
    markAllNotificationsAsRead,
    markNotificationAsRead
  }
}
