import refreshTokenHelper from "../../utils/refreshTokenHelper"
import getTokenHelper from "../../utils/getTokenHelper"
import forceLogoutHelper from "../../utils/forceLogoutHelper"
import errorHandlingHelper from "../../utils/errorHandlingHelper"
import fetchHelper from "../../utils/fetchHelper"
import laravelHelper from "../../utils/laravelHelper"
import { inOutDocKind, resolveDefaultInOutDocTypeId, docTypeFkPatch } from "../../utils/inoutDocType"

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.movementTypeId) {
    newObjValue = {...newObjValue, 
      MovementType: {
        id: body.movementTypeId,
      }
    }
  }
  if(body.docTypeId) {
    newObjValue = {...newObjValue, 
      C_DocType_ID: {
        id: body.docTypeId,
        tableName: 'C_DocType'
      }
    }
  }
  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.userId) {
    newObjValue = {...newObjValue, 
      AD_User_ID: {
        id: body.userId,
        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.returnPartnerId) {
    newObjValue = {...newObjValue, 
      Return_BPartner_ID: {
        id: body.returnPartnerId,
        tableName: 'C_BPartner'
      }
    }
  }
  if(body.returnPartnerLocationId) {
    newObjValue = {...newObjValue, 
      Return_Location_ID: {
        id: body.returnPartnerLocationId,
        tableName: 'C_BPartner_Location'
      }
    }
  }
  if(body.returnUserId) {
    newObjValue = {...newObjValue, 
      Return_User_ID: {
        id: body.returnUserId,
        tableName: 'AD_User'
      }
    }
  }
  if(body.warehouseId) {
    newObjValue = {...newObjValue, 
      M_Warehouse_ID: {
        id: body.warehouseId,
        tableName: 'M_Warehouse'
      }
    }
  }
  if(body.deliveryRuleId) {
    newObjValue = {...newObjValue, 
      DeliveryRule: {
        id: body.deliveryRuleId
      }
    }
  }
  if(body.freightCostRuleId) {
    newObjValue = {...newObjValue, 
      FreightCostRule: {
        id: body.freightCostRuleId
      }
    }
  }
  if(body.deliveryViaRuleId) {
    newObjValue = {...newObjValue, 
      DeliveryViaRule: {
        id: body.deliveryViaRuleId
      }
    }
  }
  if(body.priorityRuleId) {
    newObjValue = {...newObjValue, 
      PriorityRule: {
        id: body.priorityRuleId
      }
    }
  }
  if(body.orderId) {
    newObjValue = {...newObjValue, 
      C_Order_ID: {
        id: body.orderId,
        tableName: 'C_Order'
      }
    }
  }
  if(body.rmaId) {
    newObjValue = {...newObjValue, 
      M_RMA_ID: {
        id: body.rmaId,
        tableName: 'M_RMA'
      }
    }
  }
  if(body.docStatusId) {
    newObjValue = {...newObjValue, 
      DocStatus: {
        id: body.docStatusId
      }
    }
  }
  if(body.salesRepId) {
    newObjValue = {...newObjValue, 
      SalesRep_ID: {
        id: body.salesRepId,
        tableName: 'AD_User'
      }
    }
  }
  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.inOutLines) {
    // Add organization ID to each line to satisfy mandatory field requirement
    const processedLines = body.inOutLines.map((line: any) => ({
      ...line,
      AD_Org_ID: {
        id: body.organizationId,
        tableName: 'AD_Org'
      }
    }))

    newObjValue = {...newObjValue, 
      M_InOutLine: processedLines
    }
  }
  if(new Boolean(body.isCommissionedConfirmed)) {
    newObjValue = {...newObjValue, IsCommissionedConfirmed: body.isCommissionedConfirmed}
  }

  if(!body.docTypeId) {
    // BACKSTOP: without C_DocType_ID iDempiere rejects the create outright
    // ("FillMandatory - Document Type"). Resolve the tenant default; fail-soft
    // (unresolved → nothing merged → same error as before).
    const kind = inOutDocKind(body.isSOTrx, body.movementTypeId)
    newObjValue = {...newObjValue, ...docTypeFkPatch(await resolveDefaultInOutDocTypeId(event, kind, token))}
  }

  const res: any = await fetchHelper(event, 'models/m_inout', 'POST', token, {
    AD_Org_ID: {
      id: body.organizationId,
      tableName: 'AD_Org'
    },
    isActive: body.isActive,
    documentNo: body.documentNo,
    description: body.description,
    movementDate: body.movementDate,
    processed: body.processed,
    isSOTrx: body.isSOTrx,
    isPrinted: body.isPrinted,
    dateAcct: body.dateAcct,
    POReference: body.poReference,
    freightAmt: body.freightAmt,
    chargeAmt: body.chargeAmt,
    dateOrdered: body.dateOrdered,
    sendEMail: body.sendEMail,
    noPackages: body.noPackages,
    isInTransit: body.isInTransit,
    isApproved: body.isApproved,
    isInDispute: body.isInDispute,
    volume: body.volume,
    weight: body.weight,
    isDropShip: body.isDropShip,
    processedOn: body.processedOn,
    isAlternateReturnAddress: body.isAlternateReturnAddress,
    ...newObjValue,
    tableName: 'M_Inout'
  })
  if(res) {
    data = res
    data['status'] = 200
    data['message'] = ''

    if(body.isSOTrx === false) {
      const resp: any = await fetchHelper(event, 'models/m_inout/'+res.id+'?$expand=c_order_id,m_inoutline,c_bpartner_location_id', 'GET', token, null)
      if(resp?.C_Order_ID?.C_OrderSource_ID?.id) {
        const resp2: any = await fetchHelper(event, 'models/c_ordersource/'+resp.C_Order_ID.C_OrderSource_ID.id, 'GET', token, null)

        if(resp?.C_Order_ID?.jtl_order_id) {
            const logData = {
              jtl_order_id: resp.C_Order_ID.jtl_order_id,
              material_receipt_id: res.id,
              order_id: resp.C_Order_ID.id,
              marketplace_url: resp2?.marketplace_url
            }
            console.log('[JTL Incoming Goods] Material receipt created for JTL order:', logData)
            data['jtl_incoming_goods_log'] = { trigger: logData }

            if(resp2?.marketplace_url) {
              try {
                const requestLog = {
                  endpoint: 'sales/orders/post-jtl-incoming-goods-bulk',
                  jtl_order_id: resp.C_Order_ID.jtl_order_id
                }
                console.log('[JTL Incoming Goods] Sending bulk confirmation to JTL...', requestLog)
                data['jtl_incoming_goods_log'] = { ...data['jtl_incoming_goods_log'], request: requestLog }

                const resp4: any = await laravelHelper(event, 'sales/orders/post-jtl-incoming-goods-bulk', 'POST', {
                  orderSource: resp2,
                  id: resp.C_Order_ID.jtl_order_id
                })

                const responseLog = {
                  success: true,
                  response: resp4
                }
                console.log('[JTL Incoming Goods] Bulk confirmation response:', responseLog)
                data['jtl_incoming_goods_log'] = { ...data['jtl_incoming_goods_log'], response: responseLog }

              } catch(err: any) {
                const errorLog = {
                  error: err?.data ?? err,
                  jtl_order_id: resp.C_Order_ID.jtl_order_id
                }
                console.error('[JTL Incoming Goods] Error sending bulk confirmation:', errorLog)
                data['jtl-ffn'] = errorHandlingHelper(err?.data ?? err, err?.data ?? err)
                data['jtl_incoming_goods_log'] = { ...data['jtl_incoming_goods_log'], error: errorLog }
              }
            } else {
              const warningLog = {
                order_source_id: resp.C_Order_ID.C_OrderSource_ID.id,
                jtl_order_id: resp.C_Order_ID.jtl_order_id
              }
              console.warn('[JTL Incoming Goods] No marketplace_url configured for order source:', warningLog)
              data['jtl_incoming_goods_log'] = { ...data['jtl_incoming_goods_log'], warning: warningLog }
            }
        }
      }
    }
  }

  /*data['payload'] = {
    AD_Org_ID: {
      id: body.organizationId,
      tableName: 'AD_Org'
    },
    isActive: body.isActive,
    documentNo: body.documentNo,
    description: body.description,
    movementDate: body.movementDate,
    processed: body.processed,
    isSOTrx: body.isSOTrx,
    isPrinted: body.isPrinted,
    dateAcct: body.dateAcct,
    POReference: body.poReference,
    freightAmt: body.freightAmt,
    chargeAmt: body.chargeAmt,
    dateOrdered: body.dateOrdered,
    sendEMail: body.sendEMail,
    noPackages: body.noPackages,
    isInTransit: body.isInTransit,
    isApproved: body.isApproved,
    isInDispute: body.isInDispute,
    volume: body.volume,
    weight: body.weight,
    isDropShip: body.isDropShip,
    processedOn: body.processedOn,
    isAlternateReturnAddress: body.isAlternateReturnAddress,
    ...newObjValue,
    tableName: 'M_Inout'
  }*/

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