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

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

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

  async function getAllApplicationForms(organizationId: string): Promise<PagedApplicationFormDto> {
    return applicationFormApiClient.getAllApplicationForms({ organizationId })
  }

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

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

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

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

  return {
    createApplicationForm,
    getAllApplicationForms,
    getApplicationFormById,
    updateApplicationForm,
    deleteApplicationFormById,
    submitApplicationForm
  }
}
