import { ApplicationFormTemplateApi, Configuration } from '../../../.api-client'
import type { CreateApplicationFormDto, ApplicationFormDto, PagedApplicationFormDto } from '~~/.api-client'
import { cleanDoubleSlashes, withoutTrailingSlash } from 'ufo'
import { wrappedFetchWrap } from '~/utils/wrappedFetch'

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

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

  const applicationFormApiClient = new ApplicationFormTemplateApi(
    new Configuration({ basePath, fetchApi: wrappedFetchWrap(useRequestFetch()) })
  )

  async function createApplicationFormTemplate(
    createApplicationFormDto: CreateApplicationFormDto
  ): Promise<ApplicationFormDto> {
    return applicationFormApiClient.createApplicationFormTemplate({ createApplicationFormDto })
  }

  async function getAllApplicationFormTemplates(): Promise<PagedApplicationFormDto> {
    return applicationFormApiClient.getAllApplicationFormTemplates()
  }

  async function getApplicationFormTemplateById(id: string): Promise<ApplicationFormDto> {
    return applicationFormApiClient.getApplicationFormTemplateById({ id })
  }

  async function updateApplicationFormTemplate(
    id: string,
    applicationFormDto: ApplicationFormDto
  ): Promise<ApplicationFormDto> {
    return applicationFormApiClient.updateApplicationFormTemplate({ id, applicationFormDto })
  }

  async function deleteApplicationFormTemplateById(id: string): Promise<void> {
    return applicationFormApiClient.deleteApplicationFormTemplate({ id })
  }

  return {
    createApplicationFormTemplate,
    getAllApplicationFormTemplates,
    getApplicationFormTemplateById,
    updateApplicationFormTemplate,
    deleteApplicationFormTemplateById
  }
}
