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

const handleFunc = async (event: any, authToken: string | null = null) => {
  const token = authToken ?? await getTokenHelper(event)
  const body = await readBody(event)

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

  // Get all existing fee lines for this order
  const existingRes: any = await event.context.fetch(
    `models/cust_fulfillmentfeeline?$filter=c_order_id eq ${body.orderId}`,
    'GET', token, null
  )

  if (!existingRes?.records || existingRes.records.length === 0) {
    return { status: 400, message: 'No fee lines exist for this order. Cannot update fees without existing fee lines.' }
  }

  const newFeeAmount = parseFloat(body.feeAmount) || 0
  const currentTotal = existingRes.records.reduce((sum: number, record: any) => sum + (record.LineTotalAmt || 0), 0)

  if (newFeeAmount === currentTotal) {
    return { status: 200, message: 'Fee amount unchanged' }
  }

  // Calculate the difference and apply it to the first fee line
  const difference = newFeeAmount - currentTotal
  const firstLine = existingRes.records[0]
  const newLineTotal = (firstLine.LineTotalAmt || 0) + difference

  const updateRes: any = await event.context.fetch(
    `models/cust_fulfillmentfeeline/${firstLine.id}`,
    'PUT', token,
    {
      LineTotalAmt: newLineTotal,
      tableName: 'Cust_FulfillmentFeeLine'
    }
  )

  let data: any = {}
  if (updateRes) {
    data = updateRes
    data['status'] = 200
    data['message'] = 'Fee updated successfully'
    data['newTotal'] = newFeeAmount
  }

  return data
}

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

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

  return data
})
