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"

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',
    tableName: 'M_Inout'
  }
  if(option.paket_type) {
    trackingPayload['paket_type'] = 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', '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]
              })

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

              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 = 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.email) {
    const tokenEmail = await getTokenHelper(event)
    //@ts-ignore
    const respInout: any = await fetchHelper(event, 'models/m_inout/'+body.inOutId+'?$expand=c_order_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)
      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) {
    newObjValue = {...newObjValue, order_number: body.orderNumber}
  }
  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}
  }

  data['payload'] = {
    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,
    }
  }

  /*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,
      })
      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,
        })
        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
})