/**
 * GET /api/accounting/incoming-invoices/next-review?after=<inboxId>
 *
 * The documents waiting for review — for the review screen's ‹ › browsing (`ids`) and its
 * "complete & next" button (`nextId`).
 * Follows the inbox list order (newest first): the first open document AFTER the given one,
 * wrapping around to the top. Returns only ids (the list route carries the PDF thumbnails).
 */
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 }
  const after = Number(getQuery(event)?.after) || 0
  const all = (await listInboxDocuments(buildInboxCtx(event, token), { status: 'parsed', limit: 100 })).filter(Boolean)
  // `ids` = every open document in inbox order (newest first) — the review's ‹ › browsing
  const ids = all.map((d: any) => Number(d.id))
  const open = all.filter((d: any) => Number(d.id) !== after)
  // ids grow with creation time and the list is newest-first → "after" = the next smaller id
  const next = open.find((d: any) => Number(d.id) < after) || open[0] || null
  return { status: 200, ids, nextId: next?.id ?? null, remaining: open.length }
}

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)
    }
  }
})
