import getTokenHelper from "../../../utils/getTokenHelper"
import fetchHelper from "../../../utils/fetchHelper"
import refreshTokenHelper from "../../../utils/refreshTokenHelper"
import errorHandlingHelper from "../../../utils/errorHandlingHelper"

/**
 * Persists the multi-parcel commission allocation ("which article was scanned
 * into which parcel") onto M_InOut.commission_parcels_json.
 *
 * Carrier-independent by design: the frontend built the parcel structure from
 * its slots and merges in tracking numbers only when the carrier response
 * provided them — this route just stores the snapshot. Only called for
 * MULTI-parcel shipments (>= 2 parcels); single-parcel flows never save this.
 *
 * Body: {
 *   inOutId: number (required)
 *   parcels: Array<{                      (required, 2+)
 *     no: number
 *     weight: number                      // effective parcel total (custom or calculated), kg
 *     trackingNo: string | null
 *     items: Array<{
 *       inoutLineId, orderLineId, productId: number | null
 *       sku, name: string
 *       qty: number
 *       weight: number                    // line weight (qty x product weight), kg
 *       scannedCodes: Array<string | null> // raw codes, one per scanned unit
 *       printLabelCode: string | null     // C_OrderLine.printLabelCode snapshot
 *     }>
 *   }>
 * }
 */
const handleFunc = async (event: any, authToken: string | null = null) => {
  const token = authToken ?? await getTokenHelper(event)
  const body = await readBody(event)

  const inOutId = Number(body?.inOutId)
  const parcels = Array.isArray(body?.parcels) ? body.parcels : []
  if (!inOutId || parcels.length < 2) {
    return { status: 400, message: 'inOutId and at least 2 parcels are required' }
  }

  const totalWeight = Number(parcels
    .reduce((sum: number, p: any) => sum + Number(p?.weight || 0), 0)
    .toFixed(2))

  const payload = {
    v: 1,
    createdAt: new Date().toISOString(),
    totalWeight,
    parcels
  }

  const res = await fetchHelper(event, 'models/m_inout/' + inOutId, 'PUT', token, {
    commission_parcels_json: JSON.stringify(payload)
  })
  return { status: 200, message: 'success', id: res?.id ?? inOutId }
}

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