import refreshTokenHelper from "../../utils/refreshTokenHelper"
import forceLogoutHelper from "../../utils/forceLogoutHelper"
import errorHandlingHelper from "../../utils/errorHandlingHelper"
import { applyPeriodOfPerformance } from "../../utils/invoicePeriodOfPerformance"
import { sessionLanguage } from "../../utils/langBundle"

const handleFunc = async (event: any, authToken: any = null) => {
  let data: any = {}
  const config = useRuntimeConfig()
  const token = authToken ?? await getTokenHelper(event)
  const body = await readBody(event)

  let newObjValue = {}

  if(body.dateInvoiced) {
    newObjValue = {...newObjValue, DateInvoiced: body.dateInvoiced}
  }

  if(body.organizationId) {
    newObjValue = {...newObjValue,
      AD_Org_ID: {
        id: body.organizationId,
        tableName: 'AD_Org'
      }
    }
  }

  if(body.orderId) {
    newObjValue = {...newObjValue,
      C_Order_ID: {
        id: body.orderId,
        tableName: 'C_Order'
      }
    }
  }

  if(body.partnerId) {
    newObjValue = {...newObjValue,
      C_BPartner_ID: {
        id: body.partnerId,
        tableName: 'C_BPartner'
      }
    }
  }

  if(body.docAction) {
    newObjValue = {...newObjValue, DocAction: body.docAction}
  }

  if(body.consolidateDocument !== undefined) {
    newObjValue = {...newObjValue, ConsolidateDocument: body.consolidateDocument ? 'Y' : 'N'}
  }

  if(body.minimumAmt) {
    newObjValue = {...newObjValue, MinimumAmt: body.minimumAmt}
  }

  if(body.inOutId) {
    newObjValue = {...newObjValue,
      M_InOut_ID: {
        id: body.inOutId,
        tableName: 'M_InOut'
      }
    }
  }

  const res: any = await event.context.fetch('processes/c_invoice_generate', 'POST', token, {
    ...newObjValue,
    tableName: 'C_Invoice_Generate'
  })

  if(res) {
    data = res
    data['status'] = 200
    data['message'] = ''
  }

  // Post-process ONLY the invoices this run created (from the process logs): invoices of
  // generated fulfilment fee-invoice orders (C_Order.isFulfillmentOrder = N) get C_Invoice.period_of_performance =
  // the billed month ("August 2027", month name in the partner's language). Fail-soft on purpose — the
  // invoices already exist, and a throw here would re-run the whole process through the
  // token-refresh retry below and generate them a second time.
  if (Array.isArray(res?.logs) && res.logs.length > 0) {
    try {
      data.periodOfPerformance = await applyPeriodOfPerformance(event, token, res.logs, sessionLanguage(event))
    } catch (err: any) {
      data.periodOfPerformance = { updated: [], skipped: [], errors: [{ error: err?.message ?? String(err) }] }
    }
  }

  return data
}

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) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }

  return data
})
