import { string } from 'alga-js'
import refreshTokenHelper from "../../utils/refreshTokenHelper"
import errorHandlingHelper from "../../utils/errorHandlingHelper"
import fetchHelper from "../../utils/fetchHelper"

const handleFunc = async (event: any, authToken: any = null) => {
  const token = authToken ?? await getTokenHelper(event)
  const query = getQuery(event)
  const jfsku = (query?.jfsku as string)?.trim()
  const merchantSku = (query?.merchantSku as string)?.trim()

  if(!jfsku && !merchantSku) {
    return { status: 400, message: 'jfsku or merchantSku is required' }
  }

  try {
    // Preferred: JOIN-like lookup by m_product.jfsku, expand storages in the same call
    let product: any = null
    let qtyOnHand = 0

    if(jfsku) {
      const escaped = jfsku.replace(/'/g, "''")
      const filter = string.urlEncode(`jfsku eq '${escaped}'`)
      const res: any = await fetchHelper(
        event,
        `models/m_product?$select=${string.urlEncode('m_product_id,Name,SKU,jfsku')}&$expand=M_Storage&$filter=${filter}`,
        'GET',
        token,
        null
      )
      if(res?.records?.length) {
        product = res.records[0]
        const storages = product?.M_Storage || []
        if(Array.isArray(storages)) {
          for(const row of storages) qtyOnHand += Number(row?.QtyOnHand || 0)
        }
      }

      // Last-resort fallback: some installations used jsfsku column; try only if strict jfsku failed
      if(!product) {
        const filter2 = string.urlEncode(`jsfsku eq '${escaped}'`)
        const res2: any = await fetchHelper(
          event,
          `models/m_product?$select=${string.urlEncode('m_product_id,Name,SKU,jsfsku')}&$expand=M_Storage&$filter=${filter2}`,
          'GET',
          token,
          null
        )
        if(res2?.records?.length) {
          product = res2.records[0]
          const storages2 = product?.M_Storage || []
          if(Array.isArray(storages2)) {
            for(const row of storages2) qtyOnHand += Number(row?.QtyOnHand || 0)
          }
        }
      }
    }

    // Fallback by merchantSku (SKU) if provided and nothing matched above
    if(!product && merchantSku) {
      const escapedSku = merchantSku.replace(/'/g, "''")
      const res3: any = await fetchHelper(
        event,
        `models/m_product?$select=${string.urlEncode('m_product_id,Name,SKU,jfsku')}&$expand=M_Storage&$filter=${string.urlEncode(`SKU eq '${escapedSku}'`)}`,
        'GET',
        token,
        null
      )
      if(res3?.records?.length) {
        product = res3.records[0]
        const storages3 = product?.M_Storage || []
        if(Array.isArray(storages3)) {
          for(const row of storages3) qtyOnHand += Number(row?.QtyOnHand || 0)
        }
      }
    }

    if(!product) {
      return { status: 404, message: 'Product not found', jfsku, merchantSku, qtyOnHand: 0 }
    }

    return {
      status: 200,
      productId: Number(product?.m_product_id || product?.id),
      jfsku: product?.jfsku || jfsku || product?.jsfsku || null,
      merchantSku: product?.SKU || merchantSku || null,
      qtyOnHand
    }
  } catch (err: any) {
    const data = errorHandlingHelper(err?.data ?? err, err?.data ?? err)
    return { status: Number(data?.status || 500), message: data?.message || 'Failed to get qty on hand' }
  }
}

export default defineEventHandler(async (event) => {
  try {
    return await handleFunc(event)
  } catch (err: any) {
    try {
      const authToken = await refreshTokenHelper(event)
      return await handleFunc(event, authToken)
    } catch (error: any) {
      const data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      if([401, 402, 403, 407].includes(Number(data.status))) {
        //@ts-ignore
        setCookie(event, 'user', null)
      }
      return data
    }
  }
})
