/**
 * GET /api/accounting/incoming-invoices?status=
 * Lists inbox documents for the current org. Used by the drop page to render the
 * card grid and poll processing → ready/error transitions.
 */
import refreshTokenHelper from '../../../utils/refreshTokenHelper'
import errorHandlingHelper from '../../../utils/errorHandlingHelper'
import { listInboxDocuments } from '../../../utils/inbox/inboxDb'
import { getInboxScope, buildInboxCtx } from '../../../utils/inbox/scope'

const handleFunc = async (event: any, authToken: any = null) => {
  const token = authToken ?? await getTokenHelper(event)
  const scope = getInboxScope(event)
  if (!scope.orgId) return { status: 401, records: [] }
  const status = (getQuery(event).status as string) || undefined
  const records = await listInboxDocuments(buildInboxCtx(event, token), { status })
  return { status: 200, records }
}

export default defineEventHandler(async (event) => {
  try {
    return await handleFunc(event)
  } catch (err: any) {
    try {
      return await handleFunc(event, await refreshTokenHelper(event))
    } catch (error: any) {
      return errorHandlingHelper(err?.data ?? err, error?.data ?? error)
    }
  }
})
