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

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

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

  const notificationApiClient = new NotificationApi(
    new Configuration({ basePath, fetchApi: wrappedFetchWrap(useRequestFetch()) })
  )

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

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

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

  async function getUnreadNotificationCount(userId: string, organizationId: string): Promise<number> {
    return notificationApiClient.getUnreadNotificationCount({ userId, organizationId })
  }

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

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

  async function clearAllNotifications(organizationId: string): Promise<void> {
    return notificationApiClient.clearAllNotifications({ organizationId })
  }

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