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

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

  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
  }
}
