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

const handleFunc = async (event: any, authToken: any = null) => {
  let data: any = { records: [] }
  const token = authToken ?? await getTokenHelper(event)

  try {
    // First, get all organizations with expanded C_BPartner_ID
    const customersRes: any = await event.context.fetch(`models/ad_org?$expand=C_BPartner_ID`, 'GET', token, null)

    if (customersRes?.records && customersRes.records.length > 0) {
      // Filter organizations where C_BPartner_ID meets the criteria
      const filteredOrgs = customersRes.records.filter((org: any) => {
        const bpartner = org.C_BPartner_ID
        return bpartner && 
               bpartner.isCustomer === true && 
               bpartner.isActive === true && 
               bpartner.isFulfillmentCustomer === true && 
               bpartner.isAccountingWarehouseVolume === true
      })

      // Extract AD_Org_ID values from the filtered organizations
      const orgIds = filteredOrgs.map((org: any) => org.id).filter((id: any) => id)

      if (orgIds.length > 0) {
        // Create filter for products belonging to these organizations
        const orgFilter = orgIds.map((orgId: number) => `AD_Org_ID eq ${orgId}`).join(' OR ')
        const productFilter = `isActive eq true AND (${orgFilter})`

        // Get products from these organizations
        const productsRes: any = await event.context.fetch(`models/m_product?$filter=${string.urlEncode(productFilter)}`, 'GET', token, null)

        if (productsRes?.records) {
          // Filter products that are missing width, length, or height
          const productsWithoutDimensions = productsRes.records.filter((product: any) => {
            const width = product.Width
            const length = product.Length  
            const height = product.Height

            // Check if any dimension is null, undefined, empty string, or zero
            return !width || !length || !height || 
                   width === '' || length === '' || height === '' ||
                   Number(width) === 0 || Number(length) === 0 || Number(height) === 0
          })

          data.records = productsWithoutDimensions.map((product: any) => ({
            id: product.id,
            name: product.Name,
            sku: product.SKU,
            width: product.Width,
            length: product.Length,
            height: product.Height,
            orgId: product.AD_Org_ID?.id,
            orgName: product.AD_Org_ID?.identifier
          }))
        }
      }
    }
  } catch (error) {
    console.error('Error fetching products without dimensions:', error)
  }

  return data
}

export default defineEventHandler(async (event) => {
  let data: any = { records: [] }

  try {
    data = await handleFunc(event)
  } catch(err: any) {
    try {
      let 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
})
