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

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

  let newObjValue = {}
  if(body.docStatusId) {
    newObjValue = {...newObjValue, 
      DocStatus: {
        id: body.docStatusId,
      }
    }
  }
  if(body.docTypeId) {
    newObjValue = {...newObjValue, 
      C_DocType_ID: {
        id: body.docTypeId,
        tableName: 'C_DocType'
      }
    }
  }
  if(body.docTypeTargetId) {
    newObjValue = {...newObjValue, 
      C_DocTypeTarget_ID: {
        id: body.docTypeTargetId,
        tableName: 'C_DocTypeTarget'
      }
    }
  }
  if(body.salesRepId) {
    newObjValue = {...newObjValue, 
      SalesRep_ID: {
        id: body.salesRepId,
        tableName: 'AD_User'
      }
    }
  }
  if(body.paymentTermId) {
    newObjValue = {...newObjValue, 
      C_PaymentTerm_ID: {
        id: body.paymentTermId,
        tableName: 'C_PaymentTerm'
      }
    }
  }
  if(body.currencyId) {
    newObjValue = {...newObjValue, 
      C_Currency_ID: {
        id: body.currencyId,
        tableName: 'C_Currency'
      }
    }
  }
  if(body.invoiceRuleId) {
    newObjValue = {...newObjValue, 
      InvoiceRule: {
        id: body.invoiceRuleId
      }
    }
  }
  if(body.deliveryViaRuleId) {
    newObjValue = {...newObjValue, 
      DeliveryViaRule: {
        id: body.deliveryViaRuleId
      }
    }
  }
  if(body.deliveryRuleId) {
    newObjValue = {...newObjValue, 
      DeliveryRule: {
        id: body.deliveryRuleId
      }
    }
  }
  if(body.priorityRuleId) {
    newObjValue = {...newObjValue, 
      PriorityRule: {
        id: body.priorityRuleId
      }
    }
  }
  if(body.freightCostRuleId) {
    newObjValue = {...newObjValue, 
      FreightCostRule: {
        id: body.freightCostRuleId
      }
    }
  }
  if(body.paymentRuleId) {
    newObjValue = {...newObjValue, 
      PaymentRule: {
        id: body.paymentRuleId
      }
    }
  }
  if(body.warehouseId) {
    newObjValue = {...newObjValue, 
      M_Warehouse_ID: {
        id: body.warehouseId,
        tableName: 'M_Warehouse'
      }
    }
  }
  if(body.priceListId) {
    newObjValue = {...newObjValue, 
      M_PriceList_ID: {
        id: body.priceListId,
        tableName: 'M_PriceList'
      }
    }
  }
  if(body.partnerId) {
    newObjValue = {...newObjValue, 
      C_BPartner_ID: {
        id: body.partnerId,
        tableName: 'C_BPartner'
      }
    }
  }
  if(body.partnerLocationId) {
    newObjValue = {...newObjValue, 
      C_BPartner_Location_ID: {
        id: body.partnerLocationId,
        tableName: 'C_BPartner_Location'
      }
    }
  }
  if(body.cashLineId) {
    newObjValue = {...newObjValue, 
      C_CashLine_ID: {
        id: body.cashLineId,
        tableName: 'C_CashLine'
      }
    }
  }
  if(body.billPartnerId) {
    newObjValue = {...newObjValue, 
      Bill_BPartner_ID: {
        id: body.billPartnerId,
        tableName: 'C_BPartner'
      }
    }
  }
  if(body.billPartnerLocationId) {
    newObjValue = {...newObjValue, 
      Bill_Location_ID: {
        id: body.billPartnerLocationId,
        tableName: 'C_BPartner_Location'
      }
    }
  }
  if(body.projectId) {
    newObjValue = {...newObjValue, 
      C_Project_ID: {
        id: body.projectId,
        tableName: 'C_Project'
      }
    }
  }
  if(body.campaignId) {
    newObjValue = {...newObjValue, 
      C_Campaign_ID: {
        id: body.campaignId,
        tableName: 'C_Campaign'
      }
    }
  }
  if(body.shipperId) {
    newObjValue = {...newObjValue, 
      M_Shipper_ID: {
        id: body.shipperId,
        tableName: 'M_Shipper'
      }
    }
  }
  if(body.freightCategoryId) {
    newObjValue = {...newObjValue, 
      M_FreightCategory_ID: {
        id: body.freightCategoryId,
        tableName: 'M_FreightCategory'
      }
    }
  }
  if(body.userId) {
    newObjValue = {...newObjValue, 
      AD_User_ID: {
        id: body.userId,
        tableName: 'AD_User'
      }
    }
  }
  if(body.billUserId) {
    newObjValue = {...newObjValue, 
      Bill_User_ID: {
        id: body.billUserId,
        tableName: 'AD_User'
      }
    }
  }
  if(body.dropShipPartnerId) {
    newObjValue = {...newObjValue, 
      DropShip_BPartner_ID: {
        id: body.dropShipPartnerId,
        tableName: 'C_BPartner'
      }
    }
  }
  if(body.dropShipPartnerLocationId) {
    newObjValue = {...newObjValue, 
      DropShip_Location_ID: {
        id: body.dropShipPartnerLocationId,
        tableName: 'C_BPartner_Location'
      }
    }
  }
  if(body.dropShipUserId) {
    newObjValue = {...newObjValue, 
      DropShip_User_ID: {
        id: body.dropShipUserId,
        tableName: 'AD_User'
      }
    }
  }
  if(body.conversionTypeId) {
    newObjValue = {...newObjValue, 
      C_ConversionType_ID: {
        id: body.conversionTypeId,
        tableName: 'C_ConversionType'
      }
    }
  }
  if(body.orderSourceId) {
    newObjValue = {...newObjValue, 
      C_OrderSource_ID: {
        id: body.orderSourceId,
        tableName: 'C_OrderSource'
      }
    }
  }
  if(body.promotionCode) {
    newObjValue = {...newObjValue, 
      PromotionCode: body.promotionCode
    }
  }
  if(body.shopware6OrderId) {
    newObjValue = {...newObjValue, 
      shopware6_order_id: body.shopware6OrderId
    }
  }
  if(body.shopifyOrderId) {
    newObjValue = {...newObjValue, 
      shopify_order_id: body.shopifyOrderId
    }
  }
  if(body.xentralOrderId) {
    newObjValue = {...newObjValue, 
      xentral_order_id: body.xentralOrderId
    }
  }
  if(body.amazonOrderId) {
    newObjValue = {...newObjValue, 
      amazon_order_id: body.amazonOrderId
    }
  }
  if(body.plentyOneOrderId) {
    newObjValue = {...newObjValue, 
      plentyone_order_id: body.plentyOneOrderId
    }
  }
  if(body.externalOrderId) {
    newObjValue = {...newObjValue,
      ExternalOrderId: body.externalOrderId
    }
  }
  if(body.ebayOrderId) {
    newObjValue = {...newObjValue,
      ebay_order_id: body.ebayOrderId
    }
  }
  if(body.temuOrderId) {
    newObjValue = {...newObjValue,
      temu_order_id: body.temuOrderId
    }
  }
  if(body.jtlMerchantOrderNumber) {
    newObjValue = {...newObjValue,
      jtl_merchant_order_number: body.jtlMerchantOrderNumber
    }
  }
  if(body.periodPerformanceDate) {
    newObjValue = {...newObjValue,
      PeriodPerformanceDate: body.periodPerformanceDate
    }
  }
  // Only send when explicitly false — DB column defaults to true.
  if(body.isFulfillmentOrder === false) {
    newObjValue = {...newObjValue,
      isFulfillmentOrder: false
    }
  }
  if(body.isRelabelByFulfillmentProvider !== undefined) {
    newObjValue = {...newObjValue,
      isRelabelByFulfillmentProvider: body.isRelabelByFulfillmentProvider === true
    }
  }
  if(body.orderLines) {
    // Fetch default sales tax if any line is missing C_Tax_ID
    let defaultTaxId: any = null
    const needsDefaultTax = body.orderLines.some((item: any) => !item.C_Tax_ID)
    if(needsDefaultTax) {
      try {
        const taxRes: any = await fetchHelper(
          event,
          'models/c_tax?$filter=IsDefault eq true AND IsSalesTax eq true AND isActive eq true&$top=1',
          'GET',
          token,
          null
        )
        if(taxRes?.records?.length > 0) {
          defaultTaxId = taxRes.records[0].id
        }
      } catch(err: any) {
        console.error('Failed to fetch default sales tax:', err)
      }
    }

    newObjValue = {...newObjValue,
      C_OrderLine: body.orderLines.map((item: any) => {
        let lineItem = {
          AD_Org_ID: {
            id: body.organizationId,
            tableName: 'AD_Org'
          },
          ...item
        }
        // Apply default tax if line doesn't have one
        if(!item.C_Tax_ID && defaultTaxId) {
          lineItem = {
            ...lineItem,
            C_Tax_ID: {
              id: defaultTaxId,
              tableName: 'C_Tax'
            }
          }
        }
        return lineItem
      })
    }
  }
  /*if(body.paymentSchedules) {
    newObjValue = {...newObjValue, 
      C_OrderPaySchedule: body.paymentSchedules
    }
  }*/

  const res: any = await fetchHelper(event, 'models/c_order', 'POST', token, {
    AD_Org_ID: {
      id: body.organizationId,
      tableName: 'AD_Org'
    },
    isActive: body.isActive,
    documentNo: body.documentNo,
    description: body.description,
    isApproved: body.isApproved,
    isCreditApproved: body.isCreditApproved,
    isDelivered: body.isDelivered,
    isInvoiced: body.isInvoiced,
    isPrinted: body.isPrinted,
    isTransferred: body.isTransferred,
    dateOrdered: body.dateOrdered,
    datePromised: body.datePromised,
    dateAcct: body.dateAcct,
    freightAmt: body.freightAmt,
    totalLines: body.totalLines,
    grandTotal: body.grandTotal,
    chargeAmt: body.chargeAmt,
    processed: body.processed,
    isSOTrx: body.isSOTrx,
    isDiscountPrinted: body.isDiscountPrinted,
    isTaxIncluded: body.isTaxIncluded,
    isSelected: body.isSelected,
    sendEMail: body.sendEMail,
    isSelfService: body.isSelfService,
    isDropShip: body.isDropShip,
    processedOn: body.processedOn,
    isPayScheduleValid: body.isPayScheduleValid,
    isPriviledgedRate: body.isPriviledgedRate,
    POReference: body?.poReference || '',
    ...newObjValue,
    tableName: 'C_Order'
  })
  if(res) {
    data = res
    data['status'] = 200
    data['message'] = ''
    
    try {
      await laravelHelper(event, '/sales/orders/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
})