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"

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

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

  // Search for default locator with correct organization (optionally filter by warehouse)
  let filter = `AD_Org_ID eq ${Number(organizationId)} AND IsActive eq true AND IsDefault 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,
      isDefault: true,
      warehouseId: locator.M_Warehouse_ID?.id || locator.M_Warehouse_ID,
      organizationId: locator.AD_Org_ID?.id || locator.AD_Org_ID
    }
  } else {
    // Fallback: try to find any locator with correct organization (not default)
    let fallbackFilter = `AD_Org_ID eq ${organizationId} AND IsActive eq true`
    if (warehouseId) {
      fallbackFilter += ` AND M_Warehouse_ID eq ${warehouseId}`
    }

    const fallbackRes: any = await event.context.fetch(
      `models/m_locator?$filter=${string.urlEncode(fallbackFilter)}&$orderby=Value&$top=1`,
      'GET',
      token,
      null
    )

    if (fallbackRes?.records && fallbackRes.records.length > 0) {
      const locator = fallbackRes.records[0]
      data = {
        id: locator.id,
        code: locator.Value || locator.identifier || locator.Name,
        Value: locator.Value,
        Name: locator.Name,
        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: 'No locator found for this 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)
})
