/**
 * Original vendor document of an AP invoice = the first PDF attached to the
 * invoice record in Strapi (attachment tables PO_Invoice 3182 — where the
 * Eingangsrechnungen inbox and the Amazon Ads import attach — or C_Invoice 318).
 *
 * Used by the Lexoffice upload: for a purchase invoice the document that must
 * reach the bookkeeping is the VENDOR's original (e.g. the Amazon Ads
 * "Steuerrechnung"), not iDempiere's internal Jasper print of our own record.
 */
import strapiHelper from './strapiHelper'
import { fetchStrapiFileBytes } from './inbox/strapiAttach'

const AP_TABLE_IDS = [3182, 318]

export interface OriginalPdf { buffer: Buffer; fileName: string; url: string }

export const findInvoiceOriginalPdf = async (event: any, cInvoiceId: number): Promise<OriginalPdf | null> => {
  for (const tableId of AP_TABLE_IDS) {
    try {
      const res: any = await strapiHelper(event, `ad-attachments?filters[AD_Table_ID][$eq]=${tableId}&filters[Record_ID][$eq]=${cInvoiceId}&populate=attachment`, 'GET', null)
      const files: any[] = res?.data?.[0]?.attachment || []
      const pdf = files
        .filter((f: any) => /pdf/i.test(f?.mime || '') || /\.pdf$/i.test(f?.name || f?.url || ''))
        .sort((a: any, b: any) => String(b?.createdAt || '').localeCompare(String(a?.createdAt || '')))[0]
      if (!pdf?.url) continue
      const buffer = await fetchStrapiFileBytes(event, pdf.url)
      if (buffer?.length) return { buffer, fileName: pdf.name || `invoice-${cInvoiceId}.pdf`, url: pdf.url }
    } catch (e: any) {
      console.warn('[OriginalPdf] lookup failed for table', tableId, e?.message || e)
    }
  }
  return null
}

export default findInvoiceOriginalPdf
