// Base
import * as base from './_crud-base'

// Constants
import { uploadCode, type UploadCodeKey } from '~/lib/constants'

const path = '/api/v1/encounter-document'
const create_path = '/api/v1/upload-file'
const name = 'encounter-document'

export function create(data: any) {
  return base.create(create_path, data, name)
}

export function getList(params: any = null) {
  return base.getList(path, params, name)
}

export function getDetail(id: number | string, params?: any) {
  return base.getDetail(path, id, name, params)
}

export function update(id: number | string, data: any) {
  return base.update(path, id, data, name)
}

export function remove(id: number | string) {
  return base.remove(path, id, name)
}

export async function uploadAttachment(file: File, userId: number, key: UploadCodeKey) {
  try {
    const resolvedKey = uploadCode[key]
    if (!resolvedKey) {
      throw new Error(`Invalid upload code key: ${key}`)
    }

    // siapkan form-data body
    const formData = new FormData()
    formData.append('code', resolvedKey)
    formData.append('content', file)

    // kirim via xfetch
    const resp = await xfetch(`${path}/${userId}/upload`, 'POST', formData)

    // struktur hasil sama seperti patchPatient
    const result: any = {}
    result.success = resp.success
    result.body = (resp.body as Record<string, any>) || {}

    return result
  } catch (error) {
    console.error('Error uploading attachment:', error)
    throw new Error('Failed to upload attachment')
  }
}
