import { date } from 'alga-js'
import getTokenHelper from "../../../utils/getTokenHelper"
import refreshTokenHelper from "../../../utils/refreshTokenHelper"
import errorHandlingHelper from "../../../utils/errorHandlingHelper"
import fetchHelper from "../../../utils/fetchHelper"
import laravelHelper from "../../../utils/laravelHelper"

/**
 * Resubmit shipment confirmation to marketplaces
 * This endpoint is used when the original confirmation failed (e.g., Laravel server was offline)
 * It reads the existing tracking number and resends the confirmation without creating a new parcel
 */

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

  // Fetch the M_Inout with order details
  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) {
    return { status: 404, message: 'Shipment not found' }
  }

  if (!resp2.TrackingNo) {
    return { status: 400, message: 'No tracking number found on shipment' }
  }

  data['shipment'] = resp2
  data['status'] = 200
  data['message'] = ''

  // Get the shipping service from existing data
  const shippingService = resp2.shipping_service_name || 'DHL'
  const trackingNumber = resp2.TrackingNo
  const shippingDate = resp2.shipping_date || date.now('', '', {timeZone: 'UTC'}).replace(' ', 'T')+'Z'

  // Get customer email from order source settings
  let isSentCustomTrackingMail = false
  let customerEmail = 'notification@logyou.de'

  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)

    if (resp3) {
      isSentCustomTrackingMail = resp3?.isSentCustomTrackingMail ?? false
      // Get customer email from order's user or partner location
      const orderEmail = resp2?.C_Order_ID?.AD_User_ID?.EMail || resp2?.C_BPartner_Location_ID?.EMail
      if (orderEmail && !resp3?.isExcludetrackingmail) {
        customerEmail = orderEmail
      }

      // Build tracking URL based on shipper config
      const trackingUrl = `https://www.dhl.de/de/privatkunden/pakete-empfangen/verfolgen.html?idc=${trackingNumber}`

      // Process each marketplace
      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: [trackingNumber],
              mail: {
                email: customerEmail,
                isSentCustomTrackingMail: isSentCustomTrackingMail,
                orderNumber: resp2?.C_Order_ID?.DocumentNo ?? 0,
                name: resp2?.C_Order_ID?.C_BPartner?.identifier ?? 'Mr/Ms',
                company: 'LogYou GmbH',
                carrier: shippingService,
                lines: resp2?.m_inoutline?.filter((i: any) => i.M_Product_ID && !i.C_Charge_ID).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) {
              await fetchHelper(event, 'models/m_inout/'+option.inout_id, 'PUT', token, {
                IsCommissionedConfirmed: true,
                ack_commissioned_laravel: true,
                tableName: 'M_Inout'
              })
              data['shopware'] = { success: true }
            }
          } 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: trackingNumber,
                url: trackingUrl,
                company: 'DHL Express'
              },
              mail: {
                email: customerEmail,
                isSentCustomTrackingMail: isSentCustomTrackingMail,
                orderNumber: resp2?.C_Order_ID?.DocumentNo ?? 0,
                name: resp2?.C_Order_ID?.C_BPartner?.identifier ?? 'Mr/Ms',
                company: 'LogYou GmbH',
                carrier: shippingService,
                lines: resp2?.m_inoutline?.filter((i: any) => i.M_Product_ID && !i.C_Charge_ID).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) {
              await fetchHelper(event, 'models/m_inout/'+option.inout_id, 'PUT', token, {
                IsCommissionedConfirmed: true,
                ack_commissioned_laravel: true,
                tableName: 'M_Inout'
              })
              data['shopify'] = { success: true }
            }
          } catch(err: any) {
            data['shopify'] = errorHandlingHelper(err?.data ?? err, err?.data ?? err)
          }
        }
      }

      if(resp2?.C_Order_ID?.amazon_order_id) {
        if(resp3?.marketplace_url) {
          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: shippingDate,
                carrierCode: 'DHL',
                shippingMethod: 'Paket',
                referenceId: resp2?.DocumentNo ?? option.inout_id
              },
              trackingCodes: {
                number: trackingNumber,
                url: trackingUrl,
              },
              mail: {
                email: customerEmail,
                isSentCustomTrackingMail: isSentCustomTrackingMail,
                orderNumber: resp2?.C_Order_ID?.DocumentNo ?? 0,
                name: resp2?.C_Order_ID?.C_BPartner?.identifier ?? 'Mr/Ms',
                company: 'LogYou GmbH',
                carrier: shippingService,
                lines: resp2?.m_inoutline?.filter((i: any) => i.M_Product_ID && !i.C_Charge_ID).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) {
              await fetchHelper(event, 'models/m_inout/'+option.inout_id, 'PUT', token, {
                IsCommissionedConfirmed: true,
                ack_commissioned_laravel: true,
                tableName: 'M_Inout'
              })
              data['amazon'] = { success: true }
            }
          } 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 {
            const plentyOneWeight = resp2?.m_inoutline?.reduce((acc: any, prev: any) => Number(acc['Weight'] ?? 0) + Number(prev['Weight'] ?? 0), 0)
            // For PlentyOne multi-parcel: include additional tracking numbers from trackingnoarray
            let additionalTrackingNumbers: string[] | null = null
            if (resp2.trackingnoarray) {
              try {
                additionalTrackingNumbers = JSON.parse(resp2.trackingnoarray)
              } catch (_e) {
                additionalTrackingNumbers = null
              }
            }
            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: shippingDate,
                carrierCode: 'DHL',
                shippingMethod: 'Paket',
                referenceId: resp2?.DocumentNo ?? option.inout_id,
                weight: plentyOneWeight ?? 0
              },
              trackingCodes: {
                number: trackingNumber,
                url: trackingUrl,
                trackingNoArray: additionalTrackingNumbers && additionalTrackingNumbers.length > 0 ? additionalTrackingNumbers : null,
              },
              mail: {
                email: customerEmail,
                isSentCustomTrackingMail: isSentCustomTrackingMail,
                orderNumber: resp2?.C_Order_ID?.DocumentNo ?? 0,
                name: resp2?.C_Order_ID?.C_BPartner?.identifier ?? 'Mr/Ms',
                company: 'LogYou GmbH',
                carrier: shippingService,
                lines: resp2?.m_inoutline?.filter((i: any) => i.M_Product_ID && !i.C_Charge_ID).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 ?? ''
              }
            })

            const plentyConfirmLog = JSON.stringify({
              marketplace: 'plentyone',
              endpoint: 'sales/orders/mark-plentyone-order-delivery',
              at: new Date().toISOString(),
              ok: !!resp4,
              resp: resp4
            }).slice(0, 8000)
            if(resp4) {
              await fetchHelper(event, 'models/m_inout/'+option.inout_id, 'PUT', token, {
                IsCommissionedConfirmed: true,
                ack_commissioned_laravel: true,
                marketplace_confirm_log: plentyConfirmLog,
                tableName: 'M_Inout'
              })
              data['plentyone'] = { success: true }
            } else {
              try {
                await fetchHelper(event, 'models/m_inout/'+option.inout_id, 'PUT', token, {
                  marketplace_confirm_log: plentyConfirmLog,
                  tableName: 'M_Inout'
                })
              } catch (_logErr) {}
            }
          } catch(err: any) {
            data['plentyone'] = errorHandlingHelper(err?.data ?? err, err?.data ?? err)
            try {
              await fetchHelper(event, 'models/m_inout/'+option.inout_id, 'PUT', token, {
                marketplace_confirm_log: JSON.stringify({
                  marketplace: 'plentyone',
                  endpoint: 'sales/orders/mark-plentyone-order-delivery',
                  at: new Date().toISOString(),
                  ok: false,
                  error: err?.data ?? err?.message ?? String(err)
                }).slice(0, 8000),
                tableName: 'M_Inout'
              })
            } catch (_logErr) {}
          }
        }
      }

      if(resp2?.C_Order_ID?.jtl_order_id) {
        if(resp3?.marketplace_url) {
          try {
            const resp4: any = await laravelHelper(event, 'sales/orders/mark-jtl-order-delivery', 'POST', {
              orderSource: resp3,
              id: resp2.C_Order_ID.ExternalOrderId,
              details: {
                shippingDate: shippingDate,
                carrierCode: 'DHL',
                shippingMethod: 'Paket',
                referenceId: resp2?.DocumentNo ?? option.inout_id,
                weight: 0
              },
              trackingCodes: {
                number: trackingNumber,
                url: trackingUrl,
              },
              mail: {
                email: customerEmail,
                isSentCustomTrackingMail: isSentCustomTrackingMail,
                orderNumber: resp2?.C_Order_ID?.DocumentNo ?? 0,
                name: resp2?.C_Order_ID?.C_BPartner?.identifier ?? 'Mr/Ms',
                company: 'LogYou GmbH',
                carrier: shippingService,
                lines: resp2?.m_inoutline?.filter((i: any) => i.M_Product_ID && !i.C_Charge_ID).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) {
              await fetchHelper(event, 'models/m_inout/'+option.inout_id, 'PUT', token, {
                IsCommissionedConfirmed: true,
                ack_commissioned_laravel: true,
                tableName: 'M_Inout'
              })
              data['jtl-ffn'] = { success: true }
            }
          } catch(err: any) {
            data['jtl-ffn'] = errorHandlingHelper(err?.data ?? err, err?.data ?? err)
          }
        }
      }

      if(resp2?.C_Order_ID?.ebay_order_id) {
        try {
          const resp4: any = await laravelHelper(event, 'sales/orders/mark-ebay-order-delivery', 'POST', {
            orderSource: resp3,
            id: resp2.C_Order_ID.ebay_order_id,
            details: {
              shippingDate: shippingDate,
              carrierCode: 'DHL',
              shippingMethod: 'Paket',
              referenceId: resp2?.DocumentNo ?? option.inout_id
            },
            trackingCodes: {
              number: trackingNumber,
              url: trackingUrl,
            },
            mail: {
              email: customerEmail,
              isSentCustomTrackingMail: isSentCustomTrackingMail,
              orderNumber: resp2?.C_Order_ID?.DocumentNo ?? 0,
              name: resp2?.C_Order_ID?.C_BPartner?.identifier ?? 'Mr/Ms',
              company: 'LogYou GmbH',
              carrier: shippingService,
              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) {
            await fetchHelper(event, 'models/m_inout/'+option.inout_id, 'PUT', token, {
              IsCommissionedConfirmed: true,
              ack_commissioned_laravel: true,
              tableName: 'M_Inout'
            })
            data['ebay'] = { success: true }
          }
        } catch(err: any) {
          data['ebay'] = errorHandlingHelper(err?.data ?? err, err?.data ?? err)
        }
      }
    }
  } else {
    data['status'] = 400
    data['message'] = 'No order source found for this shipment'
  }

  return data
}

export default defineEventHandler(async (event) => {
  let data: any = {}
  const body = await readBody(event)

  if (!body.inoutId) {
    return { status: 400, message: 'inoutId is required' }
  }

  try {
    data = await resubmitConfirmation(event, null, {
      inout_id: body.inoutId
    })
  } catch(err: any) {
    try {
      // Retry with refreshed token
      let authToken: any = await refreshTokenHelper(event)
      data = await resubmitConfirmation(event, authToken, {
        inout_id: body.inoutId
      })
    } catch(error: any) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
    }
  }

  return data
})
