import { string } from 'alga-js'
import refreshTokenHelper from "../../utils/refreshTokenHelper"
import errorHandlingHelper from "../../utils/errorHandlingHelper"
import fetchHelper from "../../utils/fetchHelper"

/**
 * Consumer endpoint for printer selection across the app (dropdowns).
 *
 * Returns the active CUST_Printer rows for the current org + org-shared rows
 * (AD_Org_ID eq 0), mapped to a flat, casing-stable shape. The CUPS queue name
 * (`cupsName`) is the value to send to the print pipeline; everything else is
 * for display / smart defaults (e.g. `defaultPrintOptions`).
 *
 * Read-only — printer maintenance lives under /api/settings/printers.
 */
const readListId = (v: any): string => {
  if (v && typeof v === 'object') return String(v.id ?? '')
  return v !== undefined && v !== null ? String(v) : ''
}
const readListLabel = (v: any): string => {
  if (v && typeof v === 'object') return String(v.identifier ?? v.id ?? '')
  return v !== undefined && v !== null ? String(v) : ''
}

const mapRow = (r: any) => ({
  id: Number(r?.id),
  name: r?.Name ?? r?.name ?? '',
  value: r?.Value ?? r?.value ?? '',
  // iDempiere OData response casing varies by model — accept both.
  cupsName: (r?.CupsName ?? r?.cupsName ?? r?.cupsname ?? '') || '',
  printerType: readListId(r?.PrinterType ?? r?.printerType),
  printerTypeLabel: readListLabel(r?.PrinterType ?? r?.printerType),
  defaultPrintOptions: (r?.DefaultPrintOptions ?? r?.defaultPrintOptions ?? '') || '',
  locationDevice: (r?.LocationDevice ?? r?.locationDevice ?? '') || '',
  isDefault: r?.IsDefault ?? r?.isDefault ?? false,
  seqNo: r?.SeqNo ?? r?.seqNo ?? null,
})

const handleFunc = async (event: any, authToken: any = null) => {
  let data: any = {}
  const token = authToken ?? await getTokenHelper(event)
  const organizationId = getCookie(event, 'logship_organization_id')

  // Include org-shared rows (AD_Org_ID eq 0) so a single printer setup can
  // serve every org without duplicating rows.
  const filter = `(AD_Org_ID eq ${organizationId} or AD_Org_ID eq 0) and IsActive eq true`
  const res: any = await fetchHelper(event, `models/cust_printer?$filter=${string.urlEncode(filter)}&$orderby=${string.urlEncode('seqno asc')}`, 'GET', token, null)

  const records = Array.isArray(res?.records) ? res.records : []
  data.records = records.map(mapRow).filter((r: any) => Number.isFinite(r.id) && r.id > 0 && r.cupsName)
  return data
}

export default defineEventHandler(async (event) => {
  let data: any = { records: [] }

  try {
    data = await handleFunc(event)
  } catch(err: any) {
    try {
      let authToken: any = await refreshTokenHelper(event)
      data = await handleFunc(event, authToken)
    } catch(error: any) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      // Never break a consumer dropdown — degrade to an empty list.
      if (!Array.isArray(data?.records)) data = { ...(data || {}), records: [] }
    }
  }

  return data
})
