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

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

  try {
    // Get all storage records with product details
    const storageRes: any = await fetchHelper(event, `models/m_storage?$expand=M_Product_ID,M_Locator_ID&$filter=${string.urlEncode('QtyOnHand gt 0')}`, 'GET', token, null)

    if (storageRes?.records) {
      let totalVolume = 0

      storageRes.records.forEach((storageItem: any, index: number) => {
        const qtyOnHand = Number(storageItem.QtyOnHand) || 0
        const product = storageItem.M_Product_ID

        const debugItem = {
          index: index + 1,
          productId: product?.id,
          productName: product?.Name || 'Unknown',
          sku: product?.SKU || 'N/A',
          qtyOnHand,
          width: Number(product?.Width) || 0,
          height: Number(product?.Height) || 0,
          length: Number(product?.Length) || 0,
          singleProductVolume: 0,
          totalVolumeForProduct: 0
        }

        if (qtyOnHand > 0 && product) {
          // Helper function to convert dimensions from mm to m if no decimal present
          const convertDimension = (value: string | number): number => {
            if (!value) return 0
            const strValue = String(value)
            const numValue = Number(value)

            // If contains comma or decimal point, it's already in meters
            if (strValue.includes('.') || strValue.includes(',')) {
              return numValue
            }

            // No decimal/comma means millimeters, convert to meters
            return numValue / 1000
          }

          const width = convertDimension(product.Width)
          const height = convertDimension(product.Height)
          const length = convertDimension(product.Length)

          // Calculate single product volume: width × height × length (in m³)
          const singleProductVolume = width * height * length
          // Multiply by quantity on hand to get total volume for this product
          const totalVolumeForThisProduct = qtyOnHand * singleProductVolume

          debugItem.singleProductVolume = parseFloat(singleProductVolume.toFixed(2))
          debugItem.totalVolumeForProduct = parseFloat(totalVolumeForThisProduct.toFixed(2))

          // Add this product's total volume to the warehouse total
          totalVolume += totalVolumeForThisProduct
        }

        data.debug.push(debugItem)
      })


      data.totalVolume = totalVolume.toFixed(2)
    }
  } catch (error) {
    console.error('Error calculating warehouse volume:', error)
  }

  return data
}

export default defineEventHandler(async (event) => {
  let data: any = { totalVolume: 0, 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
})
