import {
  ApplicationFormVersionApi,
  Configuration,
  type ApplicationFormVersionDto,
  type ApplicationFormVersionListItemDto,
  type ApplicationFormDto
} from '~~/.api-client'
import { cleanDoubleSlashes, withoutTrailingSlash } from 'ufo'
import { wrappedFetchWrap } from '~/utils/wrappedFetch'

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

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

  const versionApiClient = new ApplicationFormVersionApi(
    new Configuration({ basePath, fetchApi: wrappedFetchWrap(useRequestFetch()) })
  )

  async function getVersions(applicationFormId: string): Promise<ApplicationFormVersionListItemDto[]> {
    return versionApiClient.getApplicationFormVersions({ id: applicationFormId })
  }

  async function getVersion(applicationFormId: string, versionNumber: number): Promise<ApplicationFormVersionDto> {
    return versionApiClient.getApplicationFormVersion({
      id: applicationFormId,
      versionNumber
    })
  }

  async function restoreVersion(applicationFormId: string, versionNumber: number): Promise<ApplicationFormDto> {
    return versionApiClient.restoreApplicationFormVersion({
      id: applicationFormId,
      versionNumber
    })
  }

  return {
    getVersions,
    getVersion,
    restoreVersion
  }
}
