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 sendcloudHelper from "../../../utils/sendcloudHelper"
import laravelHelper from "../../../utils/laravelHelper"
import { commissionTableFkPatch } from "../../../utils/commissionTable"

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,
    Sendcloud_Parcel_ID: option.parcel_id,
    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
  }
  // Link the commissioning table (Tisch) so the correct camera's video can be
  // resolved later. No-op when the printer is unknown/unmapped.
  Object.assign(trackingPayload, await commissionTableFkPatch(event, option.shippingPrinter, token))

  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)

        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: option.customerEmail,
                  isSentCustomTrackingMail: option.isSentCustomTrackingMail,
                  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?.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) {
                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: option.customerEmail,
                  isSentCustomTrackingMail: option.isSentCustomTrackingMail,
                  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?.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) {
                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) {
            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: 'DHL',
                  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: option.customerEmail,
                  isSentCustomTrackingMail: option.isSentCustomTrackingMail,
                  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?.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) {
                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 {
              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: 'DHL',
                  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: option.customerEmail,
                  isSentCustomTrackingMail: option.isSentCustomTrackingMail,
                  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?.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) {
                const resp5: any = await fetchHelper(event, 'models/m_inout/'+option.inout_id, 'PUT', token, {
                  IsCommissionedConfirmed: true,
                  ack_commissioned_laravel: true,
                  marketplace_confirm_log: plentyConfirmLog,
                  tableName: 'M_Inout'
                })
              } 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?.ExternalOrderId && resp3?.value === 'jtl-ffn') {
        if(resp2?.C_Order_ID?.jtl_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)
              const resp4: any = await laravelHelper(event, 'sales/orders/mark-jtl-order-delivery', 'POST', {
                orderSource: resp3,
                id: resp2.C_Order_ID.ExternalOrderId,
                details: {
                  shippingDate: trackingPayload.shipping_date,
                  carrierCode: 'DHL',
                  shippingMethod: 'Paket',
                  referenceId: resp2?.DocumentNo ?? option.inout_id,
                  weight: 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: option.customerEmail,
                  isSentCustomTrackingMail: option.isSentCustomTrackingMail,
                  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?.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) {
                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['jtl-ffn'] = errorHandlingHelper(err?.data ?? err, err?.data ?? err)
            }
          }
        }

      }
    }
  }

  return data
}

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

  let newObjValue = {}
  if(body.parcelItems) {
    newObjValue = {...newObjValue, 
      parcel_items: body.parcelItems
    }
  }
  if(body.shipmentId) {
    newObjValue = {...newObjValue, 
      shipment: {
        id: body.shipmentId
      }
    }
  }
  if(body.companyName) {
    newObjValue = {...newObjValue, company_name: body.companyName}
  }
  if(body.name2) {
    newObjValue = {...newObjValue, company_name: body.name2}
  }
  let isSentCustomTrackingMail = false
  let customerEmail = 'notification@logyou.de' //'info@logyou.de'
  const tokenEmail = await getTokenHelper(event)
  //@ts-ignore
  const respInout: any = await fetchHelper(event, 'models/m_inout/'+body.inOutId+'?$expand=c_order_id,ad_org_id', 'GET', tokenEmail, null)
  if(respInout?.C_Order_ID?.C_OrderSource_ID?.id) {
    //@ts-ignore
    const respOrderSource: any = await fetchHelper(event, 'models/c_ordersource/'+respInout.C_Order_ID.C_OrderSource_ID.id, 'GET', tokenEmail, null)
    isSentCustomTrackingMail = respOrderSource?.isSentCustomTrackingMail ?? false
    if(body.email) {
      customerEmail = respOrderSource?.isExcludetrackingmail ? 'notification@logyou.de' : body.email
      newObjValue = {...newObjValue, email: (respOrderSource?.isExcludetrackingmail ? 'notification@logyou.de' : body.email)}
    }
  }
  if(body.telephone) {
    newObjValue = {...newObjValue, telephone: body.telephone}
  }
  if(body.address2) {
    newObjValue = {...newObjValue, address_2: body.address2}
  }
  if(body.countryState) {
    newObjValue = {...newObjValue, country_state: body.countryState}
  }
  if(body.toServicePoint) {
    newObjValue = {...newObjValue, to_service_point: body.toServicePoint}
  }
  if(body.toPostNumber) {
    newObjValue = {...newObjValue, to_post_number: body.toPostNumber}
  }
  if(body.customsInvoiceNR) {
    newObjValue = {...newObjValue, customs_invoice_nr: body.customsInvoiceNR}
  }
  if(body.customsShipmentType) {
    newObjValue = {...newObjValue, customs_shipment_type: body.customsShipmentType}
  }
  if(body.weight) {
    newObjValue = {...newObjValue, weight: Number(body.weight ?? 0).toFixed(2)}
  }
  if(body.length) {
    newObjValue = {...newObjValue, length: body.length}
  }
  if(body.width) {
    newObjValue = {...newObjValue, width: body.width}
  }
  if(body.height) {
    newObjValue = {...newObjValue, height: body.height}
  }
  if(body.orderNumber) {
    // Format order number with first word of company name and sanitize special characters
    const companyName = respInout?.AD_Org_ID?.companyname ?? ''
    const firstWord = companyName.trim().split(/\s+/)[0]?.replace(/[^a-zA-Z0-9]/g, '') || ''
    const formattedOrderNumber = firstWord ? `${body.orderNumber}-${firstWord}` : body.orderNumber
    newObjValue = {...newObjValue, order_number: formattedOrderNumber}
  }
  if(body.totalOrderValue) {
    newObjValue = {...newObjValue, total_order_value: body.totalOrderValue}
  }
  if(body.totalOrderValueCurrency) {
    newObjValue = {...newObjValue, total_order_value_currency: body.totalOrderValueCurrency}
  }
  if(body.shippingMethodCheckoutName) {
    newObjValue = {...newObjValue, shipping_method_checkout_name: body.shippingMethodCheckoutName}
  }
  /*if(body.senderAddress) {
    newObjValue = {...newObjValue, sender_address: body.senderAddress}
  }*/
  if(body.quantity) {
    newObjValue = {...newObjValue, quantity: body.quantity}
  }
  if(body.totalInsuredValue) {
    newObjValue = {...newObjValue, total_insured_value: body.totalInsuredValue}
  }

  const res: any = await sendcloudHelper('parcels', 'POST', {
    parcel: {
      name: body.name,
      address: body.address,
      city: body.city,
      country: body.country,
      postal_code: String(body.postalCode),
      house_number: String(body.houseNumber || 0),
      is_return: body.isReturn,
      request_label: body.requestLabel,
      apply_shipping_rules: body.applyShippingRules,
      request_label_async: body.requestLabelAsync,
      external_reference: body.inOutId,
      ...newObjValue,
    }
  })
  if(res?.parcel) {
    data['parcel'] = res.parcel
    try {
      const res2 = await handleInoutFunc(event, null, {
        inout_id: body.inOutId,
        tracking_number: res.parcel.tracking_number,
        tracking_url: res.parcel.tracking_url,
        parcel_id: res.parcel.id,
        paket_type: body.paketType,
        shippingService: body.shippingService,
        shippingPrinter: body.shippingPrinter,
        customerEmail: customerEmail,
        isSentCustomTrackingMail: isSentCustomTrackingMail,
      })
      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: res.parcel.tracking_number,
          tracking_url: res.parcel.tracking_url,
          parcel_id: res.parcel.id,
          paket_type: body.paketType,
          shippingService: body.shippingService,
          shippingPrinter: body.shippingPrinter,
          customerEmail: customerEmail,
          isSentCustomTrackingMail: isSentCustomTrackingMail,
        })
        data = {...data, ...res3}
      } catch(error: any) {
        data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
        //forceLogoutHelper(event, data)
      }
    }
  } else {
    data['status'] = 500
    data['message'] = 'Parcel is not being created!'
  }

  return data
}

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

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

  return data
})