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

export function useApplicationFormApi() {
  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 ApplicationFormApi(
    new Configuration({ basePath, fetchApi: wrappedFetchWrap(useRequestFetch()) })
  )

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

  async function addFormElementToSection(
    applicationFormId: string,
    sectionId: string,
    createFormElementDto: CreateFormElementDto,
    position: number
  ): Promise<ApplicationFormDto> {
    return applicationFormApiClient.addFormElementToSection({
      applicationFormId,
      sectionId,
      createFormElementDto,
      position
    })
  }

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