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) {
          // Dimensions are always in mm, convert to meters
          const convertMmToM = (value: string | number): number => {
            if (!value) return 0
            // Handle comma as decimal separator
            const strValue = String(value).replace(',', '.')
            return Number(strValue) / 1000
          }

          const width = convertMmToM(product.Width)
          const height = convertMmToM(product.Height)
          const length = convertMmToM(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
})
