/**
 * POST /api/accounting/amazon-ads/void { cInvoiceId, invoiceNo }
 * Storno of a booked Ads invoice (doc-action VO) + free its DocumentNo
 * ('<no>-VOID-<id>', freeVoidedInvoiceNumbers) so the SAME Amazon invoice can be
 * imported again later. The local store forgets the import link.
 */
import { withRefresh } from '../../../utils/amazonAds/routeShared'
import getTokenHelper from '../../../utils/getTokenHelper'
import { voidAdsInvoice } from '../../../utils/amazonAds/importInvoice'
import { markVoided, getInvoice, findByCInvoiceId } from '../../../utils/amazonAds/invoiceStore'

export default withRefresh(async (event, authToken = null) => {
  const token = authToken ?? await getTokenHelper(event)
  const body = await readBody(event)
  const cInvoiceId = Number(body?.cInvoiceId || 0)
  if (!cInvoiceId) return { status: 400, message: 'cInvoiceId fehlt' }
  const r = await voidAdsInvoice(event, token, cInvoiceId)
  if (r.status === 200) {
    // the store row is bookkeeping only — a failure here must not turn a successful Storno into an error
    try {
      const row = body?.invoiceNo ? await getInvoice(event, token, String(body.invoiceNo)) : await findByCInvoiceId(event, token, cInvoiceId)
      if (row) await markVoided(event, token, row, row.invoiceNo)
    } catch (e: any) { r.warnings = [...(r.warnings || []), `Eintrag in der Rechnungsliste konnte nicht aktualisiert werden: ${e?.data?.detail || e?.message || e}`] }
  }
  return r
})
