import { ScanFactory } from './factories/scanFactory.js'
import { userService } from './userService.js'

export const uploadService = {
  async scan(file) {
    const config = useRuntimeConfig()
    const form = new FormData()
    form.append('file', file)

    const token = userService.getToken()
    const res = await fetch(`${config.public.apiBase}/api/scan`, {
      method: 'POST',
      headers: token ? { Authorization: `Bearer ${token}` } : {},
      body: form,
    })

    if (!res.ok) {
      const err = await res.json().catch(() => ({ message: 'Scan failed. Please try again.' }))
      throw new Error(err.message || 'Scan failed.')
    }

    const data = await res.json()
    return ScanFactory.fromApiResponse(data)
  },

  async convert(sessionId, filename = 'idconvert_export.json') {
    const config = useRuntimeConfig()
    const token = userService.getToken()

    const res = await fetch(`${config.public.apiBase}/api/convert`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...(token ? { Authorization: `Bearer ${token}` } : {}),
      },
      body: JSON.stringify({ session_id: sessionId, filename }),
    })

    if (!res.ok) {
      const err = await res.json().catch(() => ({ message: 'Conversion failed. Please try again.' }))
      if (err.error === 'INSUFFICIENT_CREDITS') throw new Error('INSUFFICIENT_CREDITS')
      throw new Error(err.message || 'Conversion failed.')
    }

    return res.json()
  },
}
