/**
 * POST /api/mobile/locator-ensure { organizationId, warehouseId?, code? | x,y,z? | role?: 'default'|'return' }
 * Find-or-create a locator for an org: returns the org's existing locator, or creates it
 * in the org's warehouse from the master-org template (see server/utils/locatorCatalog.ts).
 * 404 when neither the org nor the master org knows the code (typos are never created).
 * Response: lookup shape (id, code, Value, …) + `created`.
 */
import getTokenHelper from '../../utils/getTokenHelper'
import { ensureLocator, lookupShape } 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) || 0
  if (!orgId) throw createError({ statusCode: 400, statusMessage: 'organizationId is required' })
  const role = body?.role === 'default' || body?.role === 'return' ? body.role : undefined
  const code = String(body?.code || body?.search || '').trim()
  const x = body?.x !== undefined ? String(body.x) : undefined
  const y = body?.y !== undefined ? String(body.y) : undefined
  const z = body?.z !== undefined ? String(body.z) : undefined
  if (!role && !code && !(x || y || z)) throw createError({ statusCode: 400, statusMessage: 'code, x/y/z or role is required' })

  const res = await ensureLocator(event, token, { orgId, warehouseId: Number(body?.warehouseId) || null, code: code || undefined, x, y, z, role })
  if (!res) throw createError({ statusCode: 404, statusMessage: role ? 'No matching locator in the master organization' : 'Locator not found' })
  return lookupShape(res.locator, res.created)
}

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