/**
 * POST /api/mobile/locators { organizationId, warehouseId? }
 * Locator catalog of an org for the mobile / desktop pickers: the org's own active
 * locators plus every master-org locator the org does not have yet (`isVirtual: true`,
 * id `new:<code>`). Picking a virtual entry → POST /api/mobile/locator-ensure creates it.
 * Without organizationId only the warehouse's locators are returned (no preview).
 */
import getTokenHelper from '../../utils/getTokenHelper'
import { listLocatorCatalog, masterOrgId } from '../../utils/locatorCatalog'

const handleFunc = async (event: any, authToken: any = null) => {
  const token = authToken ?? await getTokenHelper(event)
  const body = await readBody(event)
  const orgId = Number(body?.organizationId) || null
  const warehouseId = Number(body?.warehouseId) || null
  if (!orgId && !warehouseId) throw createError({ statusCode: 400, statusMessage: 'organizationId or warehouseId is required' })
  const { locators, warehouseId: whId, virtualCount } = await listLocatorCatalog(event, token, { orgId, warehouseId })
  const defaultLocator = locators.find((l) => l.isDefault) || null
  return { organizationId: orgId, warehouseId: whId, masterOrgId: masterOrgId(), defaultLocatorId: defaultLocator?.id ?? null, virtualCount, locators }
}

export default defineEventHandler(async (event) => {
  return await withAuthRetry(event, handleFunc)
})
