import type { ApplicationFormVersionDto, ApplicationFormVersionListItemDto, ApplicationFormDto } from '~~/.api-client'
import { useApplicationFormVersionApi } from '~/composables'

export function useApplicationFormVersion() {
  const versionApi = useApplicationFormVersionApi()

  async function getVersions(applicationFormId: string): Promise<ApplicationFormVersionListItemDto[]> {
    try {
      return await versionApi.getVersions(applicationFormId)
    } catch (e: unknown) {
      console.error(`Failed retrieving versions for application form ${applicationFormId}:`, e)
      return Promise.reject(e)
    }
  }

  async function getVersion(applicationFormId: string, versionNumber: number): Promise<ApplicationFormVersionDto> {
    try {
      return await versionApi.getVersion(applicationFormId, versionNumber)
    } catch (e: unknown) {
      console.error(`Failed retrieving version ${versionNumber} for application form ${applicationFormId}:`, e)
      return Promise.reject(e)
    }
  }

  async function restoreVersion(applicationFormId: string, versionNumber: number): Promise<ApplicationFormDto> {
    if (!applicationFormId) {
      return Promise.reject(new Error('Application form ID missing'))
    }

    try {
      return await versionApi.restoreVersion(applicationFormId, versionNumber)
    } catch (e: unknown) {
      console.error(`Failed restoring version ${versionNumber} for application form ${applicationFormId}:`, e)
      return Promise.reject(e)
    }
  }

  return {
    getVersions,
    getVersion,
    restoreVersion
  }
}
