import type { KbxImportMapping, KbxImportSession } from '@kbx/contracts'
import { kbxApi } from '../../../../http/generated/kbxApiClient'

export const orderImportApi = {
  createSession(file: File) {
    const form = new FormData()
    form.append('file', file)
    form.append('importType', 'oms.orders.v1')
    return kbxApi.request<KbxImportSession, FormData>('common.imports.createSession', { body: form })
  },

  getSession(id: string) {
    return kbxApi.request<KbxImportSession>('common.imports.getSession', { path: { sessionId: id } })
  },

  saveMapping(id: string, mappings: KbxImportMapping[]) {
    return kbxApi.request<KbxImportSession, { mappings: KbxImportMapping[] }>('common.imports.saveMapping', {
      path: { sessionId: id }, body: { mappings },
    })
  },

  saveNamedMapping(id: string, name: string, mappings: KbxImportMapping[]) {
    return kbxApi.request<void, { name: string; mappings: KbxImportMapping[] }>('common.imports.saveNamedMapping', {
      path: { sessionId: id }, body: { name, mappings },
    })
  },

  validate(id: string) {
    return kbxApi.request<KbxImportSession>('common.imports.validate', { path: { sessionId: id } })
  },

  commit(id: string) {
    return kbxApi.request<KbxImportSession>('common.imports.commit', { path: { sessionId: id } })
  },

  async downloadTemplate() {
    const value = await kbxApi.request<Blob>('common.imports.template', {
      path: { importType: 'oms.orders.v1' }, responseType: 'blob',
    })
    downloadBlob(value, 'OMS_주문_업로드_양식.xlsx')
  },

  async downloadErrors(id: string) {
    const value = await kbxApi.request<Blob>('common.imports.errorWorkbook', {
      path: { sessionId: id }, responseType: 'blob',
    })
    downloadBlob(value, 'OMS_주문_업로드_오류.xlsx')
  },
}

function downloadBlob(value: BlobPart, fileName: string) {
  const url = URL.createObjectURL(new Blob([value]))
  const anchor = document.createElement('a')
  anchor.href = url
  anchor.download = fileName
  anchor.click()
  URL.revokeObjectURL(url)
}
