import { date } from 'alga-js'
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 dhlHelper from "../../../../utils/dhlHelper"
import dhlCustomHelper from "../../../../utils/dhlCustomHelper"

const handleInoutFunc = async (event: any, authToken: any = null, option: any) => {
  let data: any = {}
  const token = authToken ?? await getTokenHelper(event)
  const trackingPayload: any = {
    TrackingNo: option.tracking_number,
    DHL_Shipment_Code: null,
    DHL_Routing_Code: 'other',
    DHL_Label_Base64: null,
    IsCommissioned: true,
    shipping_date: date.now('', '', {timeZone: 'UTC'}).replace(' ', 'T')+'Z',
    shipping_service_name: option.shippingService,
    tableName: 'M_Inout'
  }
  if(option.paket_type) {
    trackingPayload['M_Paket_Type_ID'] = option.paket_type
  }

  const resp: any = await fetchHelper(event, 'models/m_inout/'+option.inout_id, 'PUT', token, trackingPayload)
  if(resp) {
    data['shipment'] = resp
    data['status'] = 200
    data['message'] = ''

    if(resp?.IsCommissionedConfirmed !== true) {
      const resp2: any = await fetchHelper(event, 'models/m_inout/'+option.inout_id+'?$expand=c_order_id,m_inoutline,c_bpartner_location_id', 'GET', token, null)

      if(resp2?.C_Order_ID?.C_OrderSource_ID?.id) {
        const resp3: any = await fetchHelper(event, 'models/c_ordersource/'+resp2.C_Order_ID.C_OrderSource_ID.id, 'GET', token, null)

        // Debug: Log full order source object to see all properties
        console.log('[DEBUG] Full Order Source Object (resp3):', JSON.stringify(resp3, null, 2))

        // Debug: Log order source information
        console.log('[DEBUG] Order Source Info:', {
          orderSourceId: resp2.C_Order_ID.C_OrderSource_ID.id,
          orderSourceValue: resp3?.value,
          marketplaceIdentifier: resp3?.Marketplace?.identifier,
          marketplaceUrl: resp3?.marketplace_url,
          hasShopware6: !!resp2?.C_Order_ID?.shopware6_order_id,
          hasShopify: !!resp2?.C_Order_ID?.shopify_order_id,
          hasAmazon: !!resp2?.C_Order_ID?.amazon_order_id,
          hasPlentyone: !!resp2?.C_Order_ID?.plentyone_order_id,
          hasJTLFFN: !!(resp2?.C_Order_ID?.ExternalOrderId && resp3?.Marketplace?.identifier === 'jtl-ffn'),
          externalOrderId: resp2?.C_Order_ID?.ExternalOrderId
        })

        // Add order source debug info to data
        data['orderSourceDebug'] = {
          orderSourceId: resp2.C_Order_ID.C_OrderSource_ID.id,
          orderSourceValue: resp3?.value,
          marketplaceIdentifier: resp3?.Marketplace?.identifier,
          marketplaceUrl: resp3?.marketplace_url,
          fullOrderSource: resp3,
          orderData: {
            externalOrderId: resp2?.C_Order_ID?.ExternalOrderId,
            shopware6_order_id: resp2?.C_Order_ID?.shopware6_order_id,
            shopify_order_id: resp2?.C_Order_ID?.shopify_order_id,
            amazon_order_id: resp2?.C_Order_ID?.amazon_order_id,
            plentyone_order_id: resp2?.C_Order_ID?.plentyone_order_id
          },
          detectedPlatform: resp2?.C_Order_ID?.shopware6_order_id ? 'shopware6' :
                           resp2?.C_Order_ID?.shopify_order_id ? 'shopify' :
                           resp2?.C_Order_ID?.amazon_order_id ? 'amazon' :
                           resp2?.C_Order_ID?.plentyone_order_id ? 'plentyone' :
                           (resp2?.C_Order_ID?.ExternalOrderId && resp3?.Marketplace?.identifier === 'jtl-ffn') ? 'jtl-ffn' : 'unknown'
        }

        if(resp2?.C_Order_ID?.shopware6_order_id) {
          if(resp3?.marketplace_url) {
            try {
              const resp4: any = await laravelHelper(event, 'sales/orders/mark-shopware-order-delivery', 'POST', {
                marketplace_url: resp3.marketplace_url,
                marketplace_key: resp3.marketplace_key,
                marketplace_secret: resp3.marketplace_secret,
                id: resp2.C_Order_ID.shopware6_order_id,
                trackingCodes: [option.tracking_number],
                mail: {
                  email: 'notification@logyou.de',
                  isSentCustomTrackingMail: resp3?.isSentCustomTrackingMail ?? false,
                  orderNumber: resp2?.C_Order_ID?.DocumentNo ?? 0,
                  name: resp2?.C_Order_ID?.C_BPartner?.identifier ?? 'Mr/Ms',
                  company: 'LogYou GmbH',
                  carrier: option.shippingService ?? 'DHL',
                  lines: resp2?.m_inoutline?.map((i: any) => ({
                    description: i.M_Product_ID.identifier,
                    quantity: i.QtyEntered
                  })) ?? [],
                  address1: resp2?.C_Order_ID?.C_BPartner_Location_ID?.C_Location_ID?.Address1 ?? '',
                  address2: resp2?.C_Order_ID?.C_BPartner_Location_ID?.C_Location_ID?.Address2 ?? '',
                  city: resp2?.C_Order_ID?.C_BPartner_Location_ID?.C_Location_ID?.City ?? '',
                  country: resp2?.C_Order_ID?.C_BPartner_Location_ID?.C_Location_ID?.C_Country_ID?.identifier ?? '',
                  postal: resp2?.C_Order_ID?.C_BPartner_Location_ID?.C_Location_ID?.Postal ?? ''
                }
              })

              if(resp4) {
                const resp5: any = await fetchHelper(event, 'models/m_inout/'+option.inout_id, 'PUT', token, {
                  IsCommissionedConfirmed: true,
                  ack_commissioned_laravel: true,
                  tableName: 'M_Inout'
                })
              }
            } catch(err: any) {
              data['shopware'] = errorHandlingHelper(err?.data ?? err, err?.data ?? err)
            }
          }
        }
        if(resp2?.C_Order_ID?.shopify_order_id) {
          if(resp3?.marketplace_url) {
            try {
              const resp4: any = await laravelHelper(event, 'sales/orders/mark-shopify-order-delivery', 'POST', {
                orderSource: resp3,
                id: resp2.C_Order_ID.shopify_order_id,
                trackingCodes: {
                  number: option.tracking_number,
                  url: option.tracking_url,
                  company: 'DHL Express'
                },
                mail: {
                  email: 'notification@logyou.de',
                  isSentCustomTrackingMail: resp3?.isSentCustomTrackingMail ?? false,
                  orderNumber: resp2?.C_Order_ID?.DocumentNo ?? 0,
                  name: resp2?.C_Order_ID?.C_BPartner?.identifier ?? 'Mr/Ms',
                  company: 'LogYou GmbH',
                  carrier: option.shippingService ?? 'DHL',
                  lines: resp2?.m_inoutline?.map((i: any) => ({
                    description: i.M_Product_ID.identifier,
                    quantity: i.QtyEntered
                  })) ?? [],
                  address1: resp2?.C_Order_ID?.C_BPartner_Location_ID?.C_Location_ID?.Address1 ?? '',
                  address2: resp2?.C_Order_ID?.C_BPartner_Location_ID?.C_Location_ID?.Address2 ?? '',
                  city: resp2?.C_Order_ID?.C_BPartner_Location_ID?.C_Location_ID?.City ?? '',
                  country: resp2?.C_Order_ID?.C_BPartner_Location_ID?.C_Location_ID?.C_Country_ID?.identifier ?? '',
                  postal: resp2?.C_Order_ID?.C_BPartner_Location_ID?.C_Location_ID?.Postal ?? ''
                }
              })

              if(resp4) {
                const resp5: any = await fetchHelper(event, 'models/m_inout/'+option.inout_id, 'PUT', token, {
                  IsCommissionedConfirmed: true,
                  ack_commissioned_laravel: true,
                  tableName: 'M_Inout'
                })
              }
            } catch(err: any) {
              data['shopify'] = errorHandlingHelper(err?.data ?? err, err?.data ?? err)
            }
          }
        }
        if(resp2?.C_Order_ID?.amazon_order_id) {
          if(resp3?.marketplace_url) {
            data['amazon'] = resp3
            try {
              const resp4: any = await laravelHelper(event, 'sales/orders/mark-amazon-order-delivery', 'POST', {
                orderSource: resp3,
                id: resp2.C_Order_ID.amazon_order_id,
                details: {
                  shippingDate: trackingPayload.shipping_date,
                  carrierCode: resp2?.C_Order_ID?.M_Shipper_ID?.identifier || 'Other',
                  shippingMethod: 'Paket',
                  referenceId: resp2?.DocumentNo ?? option.inout_id
                },
                trackingCodes: {
                  number: option.tracking_number,
                  url: option.tracking_url,
                  // company: 'DHL Home Delivery', // 'DHL', 'DHL eCommerce', 'DHL Express', 'DHL Freight', 'DHL Global Mail', 'DHL Home Delivery', 'DHL Kargo', 'DHL-Paket', 'DHL Parcel UK', 'DHLPL',
                },
                mail: {
                  email: 'notification@logyou.de',
                  isSentCustomTrackingMail: resp3?.isSentCustomTrackingMail ?? false,
                  orderNumber: resp2?.C_Order_ID?.DocumentNo ?? 0,
                  name: resp2?.C_Order_ID?.C_BPartner?.identifier ?? 'Mr/Ms',
                  company: 'LogYou GmbH',
                  carrier: option.shippingService ?? 'DHL',
                  lines: resp2?.m_inoutline?.map((i: any) => ({
                    description: i.M_Product_ID.identifier,
                    quantity: i.QtyEntered
                  })) ?? [],
                  address1: resp2?.C_Order_ID?.C_BPartner_Location_ID?.C_Location_ID?.Address1 ?? '',
                  address2: resp2?.C_Order_ID?.C_BPartner_Location_ID?.C_Location_ID?.Address2 ?? '',
                  city: resp2?.C_Order_ID?.C_BPartner_Location_ID?.C_Location_ID?.City ?? '',
                  country: resp2?.C_Order_ID?.C_BPartner_Location_ID?.C_Location_ID?.C_Country_ID?.identifier ?? '',
                  postal: resp2?.C_Order_ID?.C_BPartner_Location_ID?.C_Location_ID?.Postal ?? ''
                }
              })

              if(resp4) {
                const resp5: any = await fetchHelper(event, 'models/m_inout/'+option.inout_id, 'PUT', token, {
                  IsCommissionedConfirmed: true,
                  ack_commissioned_laravel: true,
                  tableName: 'M_Inout'
                })
              }
            } catch(err: any) {
              data['amazon'] = errorHandlingHelper(err?.data ?? err, err?.data ?? err)
            }
          }
        }
        if(resp2?.C_Order_ID?.plentyone_order_id) {
          if(resp3?.marketplace_url) {
            try {
              data['plentyone'] = resp3
              const plentyOneWeight = resp2?.m_inoutline?.reduce((acc: any, prev: any) => Number(acc['Weight'] ?? 0) + Number(prev['Weight'] ?? 0), 0)
              const resp4: any = await laravelHelper(event, 'sales/orders/mark-plentyone-order-delivery', 'POST', {
                orderSource: resp3,
                id: resp2.C_Order_ID.plentyone_order_id,
                details: {
                  shippingDate: trackingPayload.shipping_date,
                  carrierCode: resp2?.C_Order_ID?.M_Shipper_ID?.identifier || 'Other',
                  shippingMethod: 'Paket',
                  referenceId: resp2?.DocumentNo ?? option.inout_id,
                  weight: plentyOneWeight ?? 0
                },
                trackingCodes: {
                  number: option.tracking_number,
                  url: option.tracking_url,
                  // company: 'DHL Home Delivery', // 'DHL', 'DHL eCommerce', 'DHL Express', 'DHL Freight', 'DHL Global Mail', 'DHL Home Delivery', 'DHL Kargo', 'DHL-Paket', 'DHL Parcel UK', 'DHLPL',
                },
                mail: {
                  email: 'notification@logyou.de',
                  isSentCustomTrackingMail: resp3?.isSentCustomTrackingMail ?? false,
                  orderNumber: resp2?.C_Order_ID?.DocumentNo ?? 0,
                  name: resp2?.C_Order_ID?.C_BPartner?.identifier ?? 'Mr/Ms',
                  company: 'LogYou GmbH',
                  carrier: option.shippingService ?? 'DHL',
                  lines: resp2?.m_inoutline?.map((i: any) => ({
                    description: i.M_Product_ID.identifier,
                    quantity: i.QtyEntered
                  })) ?? [],
                  address1: resp2?.C_Order_ID?.C_BPartner_Location_ID?.C_Location_ID?.Address1 ?? '',
                  address2: resp2?.C_Order_ID?.C_BPartner_Location_ID?.C_Location_ID?.Address2 ?? '',
                  city: resp2?.C_Order_ID?.C_BPartner_Location_ID?.C_Location_ID?.City ?? '',
                  country: resp2?.C_Order_ID?.C_BPartner_Location_ID?.C_Location_ID?.C_Country_ID?.identifier ?? '',
                  postal: resp2?.C_Order_ID?.C_BPartner_Location_ID?.C_Location_ID?.Postal ?? ''
                }
              })
              data['plentyone_laravel'] = resp4
              if(resp4) {
                const resp5: any = await fetchHelper(event, 'models/m_inout/'+option.inout_id, 'PUT', token, {
                  IsCommissionedConfirmed: true,
                  ack_commissioned_laravel: true,
                  tableName: 'M_Inout'
                })
              }
            } catch(err: any) {
              data['plentyone'] = errorHandlingHelper(err?.data ?? err, err?.data ?? err)
            }
          }
        }
        if(resp2?.C_Order_ID?.ExternalOrderId && resp3?.Marketplace?.identifier === 'jtl-ffn') {
          console.log('[DEBUG] JTL-FFN Order Detected:', {
            externalOrderId: resp2.C_Order_ID.ExternalOrderId,
            orderSourceValue: resp3?.value,
            marketplaceIdentifier: resp3?.Marketplace?.identifier,
            marketplaceUrl: resp3?.marketplace_url,
            endpoint: 'sales/orders/mark-jtl-order-delivery',
            hasMarketplaceUrl: !!resp3?.marketplace_url
          })

          if(resp3?.marketplace_url) {
            console.log('[DEBUG] JTL-FFN: Sending order confirmation to Laravel endpoint:', {
              endpoint: 'sales/orders/mark-jtl-order-delivery',
              marketplaceUrl: resp3.marketplace_url,
              orderId: resp2.C_Order_ID.ExternalOrderId,
              trackingNumber: option.tracking_number
            })

            console.log('[DEBUG] JTL-FFN: Building payload...')
            console.log('[DEBUG] JTL-FFN: resp3 keys:', Object.keys(resp3 || {}))
            console.log('[DEBUG] JTL-FFN: resp3.IsCustomTrackingMail:', resp3?.IsCustomTrackingMail)
            console.log('[DEBUG] JTL-FFN: resp3.isSentCustomTrackingMail:', resp3?.isSentCustomTrackingMail)

            try {
              const jtlPayload = {
                orderSource: resp3,
                id: resp2.C_Order_ID.ExternalOrderId,
                details: {
                  shippingDate: trackingPayload.shipping_date,
                  carrierCode: resp2?.C_Order_ID?.M_Shipper_ID?.identifier || 'Other',
                  shippingMethod: 'Paket',
                  referenceId: resp2?.DocumentNo ?? option.inout_id,
                  weight: 0
                },
                trackingCodes: {
                  number: option.tracking_number,
                  url: option.tracking_url,
                },
                mail: {
                  email: 'notification@logyou.de',
                  isSentCustomTrackingMail: resp3?.isSentCustomTrackingMail ?? false,
                  IsCustomTrackingMail: resp3?.IsCustomTrackingMail ?? false,
                  orderNumber: resp2?.C_Order_ID?.DocumentNo ?? 0,
                  name: resp2?.C_Order_ID?.C_BPartner?.identifier ?? 'Mr/Ms',
                  company: 'LogYou GmbH',
                  carrier: option.shippingService ?? 'DHL',
                  lines: resp2?.m_inoutline?.map((i: any) => ({
                    description: i.M_Product_ID.identifier,
                    quantity: i.QtyEntered
                  })) ?? [],
                  address1: resp2?.C_Order_ID?.C_BPartner_Location_ID?.C_Location_ID?.Address1 ?? '',
                  address2: resp2?.C_Order_ID?.C_BPartner_Location_ID?.C_Location_ID?.Address2 ?? '',
                  city: resp2?.C_Order_ID?.C_BPartner_Location_ID?.C_Location_ID?.City ?? '',
                  country: resp2?.C_Order_ID?.C_BPartner_Location_ID?.C_Location_ID?.C_Country_ID?.identifier ?? '',
                  postal: resp2?.C_Order_ID?.C_BPartner_Location_ID?.C_Location_ID?.Postal ?? ''
                }
              }

              console.log('[DEBUG] JTL-FFN: Payload being sent to Laravel:', JSON.stringify(jtlPayload, null, 2))

              console.log('[DEBUG] JTL-FFN: About to call laravelHelper...')
              const resp4: any = await laravelHelper(event, 'sales/orders/mark-jtl-order-delivery', 'POST', jtlPayload)
              console.log('[DEBUG] JTL-FFN: laravelHelper call completed')

              console.log('[DEBUG] JTL-FFN: Laravel response:', {
                success: !!resp4,
                response: resp4
              })

              data['jtl_laravel'] = resp4

              if(resp4) {
                console.log('[DEBUG] JTL-FFN: Marking order as commissioned confirmed')
                const resp5: any = await fetchHelper(event, 'models/m_inout/'+option.inout_id, 'PUT', token, {
                  IsCommissionedConfirmed: true,
                  ack_commissioned_laravel: true,
                  tableName: 'M_Inout'
                })
              }
            } catch(err: any) {
              console.error('[DEBUG] JTL-FFN: Error during order confirmation:', err)
              data['jtl'] = errorHandlingHelper(err?.data ?? err, err?.data ?? err)
            }
          } else {
            console.warn('[DEBUG] JTL-FFN: No marketplace_url configured for order source')
            data['jtl_warning'] = 'No marketplace_url configured for JTL-FFN order source'
          }
        }

      }
    }
  }

  return data
}

const handleFunc = async (event: any) => {
  let data: any = {}
  const config = useRuntimeConfig()
  const body = await readBody(event)

  let refNo = body.orderNumber ?? body.inOutUId.replaceAll('-', '')
  let refNoDigit = ''
  if(refNo.length < 9) {
    refNoDigit = '0'
    for(let i = 0; i < (9 - Number(refNo.length)); i++) {
      refNoDigit += '0'
      refNo = `${refNoDigit}${refNo}`
    }
  }

  try {
    const res2 = await handleInoutFunc(event, null, {
      inout_id: body.inOutId,
      tracking_number: body.trackingNo ?? refNo,
      tracking_url: '',
      shipment_code: body.trackingNo ?? refNo,
      routing_code: '',
      label_base64: '',
      paket_type: body.paketType,
      shippingService: body.shippingService
    })
    data = {...data, ...res2}
  } catch(err: any) {
    try {
      let authToken: any = await refreshTokenHelper(event)
      const res3 = await handleInoutFunc(event, authToken, {
        inout_id: body.inOutId,
        tracking_number: body.trackingNo ?? refNo,
        tracking_url: '',
        shipment_code: body.trackingNo ?? refNo,
        routing_code: '',
        label_base64: '',
        paket_type: body.paketType,
        shippingService: body.shippingService
      })
      data = {...data, ...res3}
    } catch(error: any) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      //forceLogoutHelper(event, data)
    }
  }

  return data
}

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

  try {
    data = await handleFunc(event)
  } catch(err: any) {
    data = errorHandlingHelper(err?.data ?? err, err?.data ?? err)
  }

  return data
})