import type { AxiosResponse } from 'axios'
import download from 'js-file-download'
import config from '@/config'

import request from '@/utils/request'
import type { Accessory } from '@/types/accessory'
import { SuccessResultCode, type Result } from '@cacp/ui'

const contextPath = '/accessory'

export function getUploadUrl(): string {
  if (config.SERVICE_API.endsWith('/')) {
    return `${config.SERVICE_API.substring(0, config.SERVICE_API.length - 1)}${contextPath}/upload-file`
  } else {
    return `${config.SERVICE_API}/${contextPath}/upload-file`
  }
}

export function getDownloadUrl(accessoryId: string): string {
  if (config.SERVICE_API.endsWith('/')) {
    return `${config.SERVICE_API.substring(0, config.SERVICE_API.length - 1)}${contextPath}/download-file?accessoryId=${accessoryId}`
  } else {
    return `${config.SERVICE_API}${contextPath}/download-file?accessoryId=${accessoryId}`
  }
}

export async function downloadFile(accessoryId: string, fileName: string): Promise<void> {
  const res: AxiosResponse<Result<any>> = await request.get(`${contextPath}/download-file`, {
    params: { accessoryId: accessoryId },
    responseType: 'arraybuffer'
  })

  if (res.data.code === SuccessResultCode) {
    download(res.data.data, fileName, 'application/octet-stream')
  }
}

export async function deleteFile(accessoryId: string): Promise<Result<number>> {
  const res: AxiosResponse<Result<number>> = await request.post(`${contextPath}/delete-file`, {
    params: { accessoryId: accessoryId }
  })
  return res.data
}

export async function getPersistListByBizId(bizId: string): Promise<Result<Array<Accessory>>> {
  const res: AxiosResponse<Result<Array<Accessory>>> = await request.get(`${contextPath}/get-persist-list-by-biz-id`, {
    params: { bizId: bizId }
  })
  return res.data
}

export async function getPersistListByRelId(bizId: string, relId: string): Promise<Result<Array<Accessory>>> {
  const res: AxiosResponse<Result<Array<Accessory>>> = await request.get(`${contextPath}/get-persist-list-by-rel-id`, {
    params: { bizId: bizId, relId: relId }
  })
  return res.data
}
