/**
 * GET /api/commission/tables
 *
 * Active commissioning tables (Tische) for the current org, used to populate
 * the table/printer picker on the commissioning page (desktop + mobile) and
 * in CommissionModal. Backed by CUST_CommissionTable via the cached util, so
 * the picker stays in sync with Settings → Commission Tables with no code change.
 *
 * Returns { records: [{ id, number, name, shippingPrinter, a4Printer, cameraId }] }
 * sorted by table number. Empty list (table not set up yet / fetch failed) lets
 * the client fall back to its built-in Tisch 1/2/3 defaults.
 */

import refreshTokenHelper from "../../utils/refreshTokenHelper"
import errorHandlingHelper from "../../utils/errorHandlingHelper"
import { getCommissionTables } from "../../utils/commissionTable"

const handleFunc = async (event: any, authToken: any = null) => {
  const token = authToken ?? await getTokenHelper(event)
  const orgId = Number(getCookie(event, 'logship_organization_id'))

  const rows = await getCommissionTables(event, orgId, token)
  const records = [...rows]
    .filter(r => r.shippingPrinter)
    .sort((a, b) => (a.number ?? 9999) - (b.number ?? 9999) || a.name.localeCompare(b.name))

  return { records }
}

export default defineEventHandler(async (event) => {
  try {
    return await handleFunc(event)
  } catch(err: any) {
    try {
      const authToken: any = await refreshTokenHelper(event)
      return await handleFunc(event, authToken)
    } catch(error: any) {
      // Never break the picker — fall back to an empty list (client uses defaults).
      return { records: [], error: errorHandlingHelper(err?.data ?? err, error?.data ?? error) }
    }
  }
})
