import { CommentApi, Configuration, type CommentDto, type CreateCommentDto, type PagedCommentDto } from '~/.api-client'
import { cleanDoubleSlashes, withoutTrailingSlash } from 'ufo'

export function useCommentApi() {
  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 commentApiClient = new CommentApi(
    new Configuration({ basePath, headers: { Authorization: jwt.value ? `Bearer ${jwt.value}` : '' } })
  )

  async function createComment(
    applicationFormId: string,
    formElementId: string,
    createCommentDto: CreateCommentDto
  ): Promise<CommentDto> {
    return commentApiClient.createComment({ applicationFormId, formElementId, createCommentDto })
  }

  async function getCommentsByApplicationFormId(applicationFormId: string): Promise<PagedCommentDto> {
    return commentApiClient.getCommentsByApplicationFormId({ applicationFormId })
  }

  async function updateComment(id: string, commentDto: CommentDto): Promise<CommentDto> {
    return commentApiClient.updateComment({ id, commentDto })
  }

  async function deleteCommentById(id: string): Promise<void> {
    return commentApiClient.deleteComment({ id })
  }

  return {
    createComment,
    getCommentsByApplicationFormId,
    updateComment,
    deleteCommentById
  }
}
