import refreshTokenHelper from "../../../utils/refreshTokenHelper"
import forceLogoutHelper from "../../../utils/forceLogoutHelper"
import errorHandlingHelper from "../../../utils/errorHandlingHelper"
import getTokenHelper from "../../../utils/getTokenHelper"
import { listLocatorCatalog } from "../../../utils/locatorCatalog"

/**
 * Mobile reconditioning — target locators of an org (optionally one warehouse), with
 * the locator-type flags so the picker can mark shippable bins. The org's IsDefault
 * locator is returned first (the page preselects it).
 */
const handleFunc = async (event: any, authToken: any = null) => {
  const token = authToken ?? await getTokenHelper(event)
  const body = await readBody(event)
  const orgId = Number(body?.organizationId)
  const warehouseId = Number(body?.warehouseId) || null
  if (!(orgId > 0)) {
    throw createError({ statusCode: 400, statusMessage: 'organizationId is required' })
  }
  // Org locators + master-org preview (isVirtual, id `new:<code>`, created on pick via
  // /api/mobile/locator-ensure); the org's IsDefault locator stays first.
  const { locators, warehouseId: whId, virtualCount } = await listLocatorCatalog(event, token, { orgId, warehouseId })
  locators.sort((a: any, b: any) => (b.isDefault ? 1 : 0) - (a.isDefault ? 1 : 0) || a.code.localeCompare(b.code, 'de', { numeric: true }))
  const defaultLocator = locators.find((l: any) => l.isDefault) || null
  return { organizationId: orgId, warehouseId: whId, defaultLocatorId: defaultLocator?.id ?? null, virtualCount, locators }
}

export default defineEventHandler(async (event) => {
  let data: any = {}
  try {
    data = await handleFunc(event)
  } catch (err: any) {
    if (err?.statusCode === 400) throw err
    try {
      const authToken: any = await refreshTokenHelper(event)
      data = await handleFunc(event, authToken)
    } catch (error: any) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }
  return data
})
