import { saveAs } from 'file-saver'
import axios from 'axios'
import { api } from '@/core/services/api'
import { buildCardDownloadFileName } from '../utils/member-digital-card.utils'

export async function downloadMemberDigitalCard(
  memberNumber: string | number | null | undefined,
  side: 'depan' | 'belakang',
) {
  try {
    const { data } = await api.get<Blob>('/v1/profile/digital-card', {
      params: { side },
      responseType: 'blob',
    })

    saveAs(data, buildCardDownloadFileName(memberNumber, side))
  } catch (error) {
    if (axios.isAxiosError(error) && error.response?.data instanceof Blob) {
      const text = await error.response.data.text()

      try {
        const payload = JSON.parse(text) as { message?: string }
        throw new Error(payload.message ?? 'Gagal menyimpan kad.')
      } catch (parseError) {
        if (parseError instanceof SyntaxError) {
          throw error
        }

        throw parseError
      }
    }

    throw error
  }
}
