import refreshTokenHelper from "../../../utils/refreshTokenHelper"
import forceLogoutHelper from "../../../utils/forceLogoutHelper"
import errorHandlingHelper from "../../../utils/errorHandlingHelper"
import fetchHelper from "../../../utils/fetchHelper"
import strapiHelper from "../../../utils/strapiHelper"
import laravelHelper from "../../../utils/laravelHelper"

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

  let newObjValue = {}
  if(body.uomId) {
    newObjValue = {...newObjValue, C_UOM_ID: {
      id: body.uomId,
      tableName: 'C_UOM'
    }}
  }
  if(body.productCategoryId) {
    newObjValue = {...newObjValue, M_Product_Category_ID: {
      id: body.productCategoryId,
      tableName: 'M_Product_Category'
    }}
  }
  if(body.taxCategoryId) {
    newObjValue = {...newObjValue, C_TaxCategory_ID: {
      id: body.taxCategoryId,
      tableName: 'C_TaxCategory'
    }}
  }
  if(body.productTypeId) {
    newObjValue = {...newObjValue, ProductType: {
      id: body.productTypeId
    }}
  }
  if(body.attributeSetId) {
    newObjValue = {...newObjValue, M_AttributeSet_ID: {
      id: body.attributeSetId,
      tableName: 'M_AttributeSet'
    }}
  }
  if(body.attributeSetInstanceId) {
    newObjValue = {...newObjValue, M_AttributeSetInstance_ID: {
      id: body.attributeSetInstanceId,
      tableName: 'M_AttributeSetInstance'
    }}
  }
  if(body.revenueRecognitionId) {
    newObjValue = {...newObjValue, C_RevenueRecognition_ID: {
      id: body.revenueRecognitionId,
      tableName: 'C_RevenueRecognition'
    }}
  }
  if(body.salesRepId) {
    newObjValue = {...newObjValue, SalesRep_ID: {
      id: body.salesRepId,
      tableName: 'AD_User'
    }}
  }
  if(body.mailTextId) {
    newObjValue = {...newObjValue, R_MailText_ID: {
      id: body.mailTextId,
      tableName: 'R_Mailtext'
    }}
  }
  if(body.labelPrinterId) {
    newObjValue = {...newObjValue, labelprinter: {
      id: body.labelPrinterId
    }}
  }
  if(body.labelPrinterRmaId) {
    newObjValue = {...newObjValue, labelprinter_rma: {
      id: body.labelPrinterRmaId
    }}
  }
  if(body.paketTypeId) {
    newObjValue = {...newObjValue, M_Paket_Type_ID: {
      id: body.paketTypeId,
      tableName: 'M_Product'
    }}
  }
  if(body.pickListCode !== undefined && body.pickListCode !== '') {
    newObjValue = {...newObjValue, pickListCode: body.pickListCode}
  }
  if(body.asin) {
    newObjValue = {...newObjValue, asin: body.asin}
  }
  if(body.mpn) {
    newObjValue = {...newObjValue, mpn: body.mpn}
  }
  if(body.fnsku) {
    newObjValue = {...newObjValue, fnsku: body.fnsku}
  }
  // Custom columns (exact iDempiere ColumnName casing) — only sent when the caller
  // provides them, so older callers/envs without the columns stay unaffected.
  if(body.upc2) {
    newObjValue = {...newObjValue, UPC2: body.upc2}
  }
  if(body.netWeight !== undefined && body.netWeight !== '') {
    newObjValue = {...newObjValue, netWeight: body.netWeight}
  }
  if(body.isEnabledBom !== undefined) {
    newObjValue = {...newObjValue, isEnabledBom: body.isEnabledBom}
  }
  if(body.isAutoCommission !== undefined) {
    newObjValue = {...newObjValue, isAutoCommission: body.isAutoCommission}
  }
  if(body.volume || (body.width && body.length && body.height)) {
    newObjValue = {
      ...newObjValue, 
      width: body.width || 0,
      length: body.length || 0, 
      height: body.height || 0,
      volume: body.volume || (Number(body.length || 0) * Number(body.width || 0) * Number(body.height || 0)),
    }
  }

  const res: any = await fetchHelper(event, 'models/m_product', 'POST', token, {
    AD_Org_ID: {
      id: body.organizationId,
      tableName: 'AD_Org'
    },
    isActive: body.isActive,
    name: body.name,
    SKU: body.sku,
    UPC: body.upc,
    value: body.value,
    versionNo: body.versionNo,
    description: body.description,
    help: body.help,
    documentNote: body.documentNote,
    isSummary: body.isSummary,
    isStocked: body.isStocked,
    isPurchased: body.isPurchased,
    isSold: body.isSold,
    weight: body.weight,
    discontinued: body.discontinued,
    isBOM: body.isBOM,
    isInvoicePrintDetails: body.isInvoicePrintDetails,
    isPickListPrintDetails: body.isPickListPrintDetails,
    isVerified: body.isVerified,
    guaranteeDaysMin: body.guaranteeDaysMin,
    isWebStoreFeatured: body.isWebStoreFeatured,
    isSelfService: body.isSelfService,
    isDropShip: body.isDropShip,
    isExcludeAutoDelivery: body.isExcludeAutoDelivery,
    unitsPerPack: body.unitsPerPack,
    lowLevel: body.lowLevel,
    isKanban: body.isKanban,
    isManufactured: body.isManufactured,
    isPhantom: body.isPhantom,
    isOwnBox: body.isOwnBox,
    isAutoProduce: body.isAutoProduce,
    shelfWidth: body.shelfWidth,
    shelfHeight: body.shelfHeight,
    shelfDepth: body.shelfDepth,
    unitsPerPallet: body.unitsPerPallet,
    classification: body.classification,
    customsTariffNumber: body.customsTariffNumber,
    group1: body.group1,
    group2: body.group2,
    ...newObjValue,
    tableName: 'M_Product'
  })
  if(res) {
    data = res
    data['status'] = 200
    data['message'] = ''

    const response: any = await strapiHelper(event, 'm-products', 'POST', {
      data: {
        M_Product_ID: res.id,
        value: res.Value,
        name: res.Name,
        //Main_Image: 0
      }
    })
    if(response?.data) {
      await fetchHelper(event, 'models/m_product/'+res.id, 'PUT', token, {
        Strapi_Product_ID: response.data.id,
        Strapi_Product_documentId: response.data.documentId
      })
    }

    try {
      await laravelHelper(event, '/inventories/products/sync-idempiere', 'POST', null)
    } catch(err: any) {}
  }

  return data
}

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

  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
})