import { string } from 'alga-js'
import refreshTokenHelper from "../../utils/refreshTokenHelper"
import forceLogoutHelper from "../../utils/forceLogoutHelper"
import errorHandlingHelper from "../../utils/errorHandlingHelper"
import getTokenHelper from "../../utils/getTokenHelper"
import { odataQuote } from "../../utils/odataHelper"

const handleFunc = async (event: any, authToken: any = null) => {
  let data: any = {}
  const token = authToken ?? await getTokenHelper(event)
  const body = await readBody(event)
  const x = body?.x
  const y = body?.y
  const z = body?.z
  const warehouseId = body?.warehouseId
  const organizationId = body?.organizationId

  if (!x || !y || !z) {
    throw createError({
      statusCode: 400,
      statusMessage: 'X, Y, Z coordinates are required'
    })
  }

  if (!organizationId) {
    throw createError({
      statusCode: 400,
      statusMessage: 'Organization ID is required'
    })
  }

  // Search by X, Y, Z coordinates with correct organization
  // (string literals quote-escaped, id params coerced to numbers)
  let filter = `X eq '${odataQuote(x)}' AND Y eq '${odataQuote(y)}' AND Z eq '${odataQuote(z)}' AND AD_Org_ID eq ${Number(organizationId)} AND IsActive eq true`
  if (warehouseId) {
    filter += ` AND M_Warehouse_ID eq ${Number(warehouseId)}`
  }

  const res: any = await event.context.fetch(
    `models/m_locator?$filter=${string.urlEncode(filter)}`,
    'GET',
    token,
    null
  )

  if (res?.records && res.records.length > 0) {
    const locator = res.records[0]
    data = {
      id: locator.id,
      code: locator.Value || locator.identifier || locator.Name,
      Value: locator.Value,
      Name: locator.Name,
      X: locator.X,
      Y: locator.Y,
      Z: locator.Z,
      isDefault: locator.IsDefault || false,
      warehouseId: locator.M_Warehouse_ID?.id || locator.M_Warehouse_ID,
      organizationId: locator.AD_Org_ID?.id || locator.AD_Org_ID
    }
  } else {
    throw createError({
      statusCode: 404,
      statusMessage: 'Locator not found with these coordinates and organization'
    })
  }

  return data
}

export default defineEventHandler(async (event) => {
  // Auth-only retry: a business 404 no longer triggers a token refresh.
  return await withAuthRetry(event, handleFunc)
})
