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

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.inOutLineId) {
    newObjValue = {...newObjValue, 
      M_InOutLine_ID: {
        id: body.inOutLineId,
        tableName: 'M_InOutLine'
      }
    }
  }
  if(body.taxId) {
    newObjValue = {...newObjValue, 
      C_Tax_ID: {
        id: body.taxId,
        tableName: 'C_Tax'
      }
    }
  }
  if(body.chargeId) {
    newObjValue = {...newObjValue, 
      C_Charge_ID: {
        id: body.chargeId,
        tableName: 'C_Charge'
      }
    }
  }

  if(body.rmaId && body.productId) {
    const res: any = await event.context.fetch('models/m_rmaline', 'POST', token, {
      AD_Org_ID: {
        id: body.organizationId,
        tableName: 'AD_Org'
      },
      isActive: body.isActive,
      qty: body.qty,
      processed: body.processed,
      amt: body.amt,
      line: body.line,
      lineNetAmt: Number(body.lineNetAmt || 0),
      description: body.description,
      M_RMA_ID: {
        id: body.rmaId,
        tableName: 'M_RMA'
      },
      M_Product_ID: {
        id: body.productId,
        tableName: 'M_Product'
      },
      ...newObjValue,
      tableName: 'm_rmaline'
    })
    if(res) {
      data = res
      data['status'] = 200
      data['message'] = ''
    }
  }

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

  return data
})