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"

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.warehouseId) {
    newObjValue = {...newObjValue, M_Warehouse_ID: {
      id: body.warehouseId,
      tableName: 'M_Warehouse'
    }}
  }
  if(body.docTypeId) {
    newObjValue = {...newObjValue, C_DocType_ID: {
      id: body.docTypeId,
      tableName: 'C_DocType'
    }}
  }
  if(body.projectId) {
    newObjValue = {...newObjValue, C_Project_ID: {
      id: body.projectId,
      tableName: 'C_Project'
    }}
  }
  if(body.campaignId) {
    newObjValue = {...newObjValue, C_Campaign_ID: {
      id: body.campaignId,
      tableName: 'C_Campaign'
    }}
  }
  if(body.docStatusId) {
    newObjValue = {...newObjValue, DocStatus: {
      id: body.docStatusId
    }}
  }
  if(body.inventoryLines) {
    newObjValue = {...newObjValue, m_inventoryline: body.inventoryLines}
  }

  const res: any = await fetchHelper(event, 'models/m_inventory', 'POST', token, {
    AD_Org_ID: {
      id: body.organizationId,
      tableName: 'AD_Org'
    },
    isActive: body.isActive,
    documentNo: body.documentNo,
    movementDate: body.movementDate,
    approvalAmt: body.approvalAmt,
    isApproved: body.isApproved,
    description: body.description,
    processed: body.processed,
    processing: body.processing,
    ...newObjValue,
    tableName: 'm_inventory'
  })
  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
})