import refreshTokenHelper from "../../../utils/refreshTokenHelper"
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.userId) {
    newObjValue = {...newObjValue, 
      AD_User_ID: {
        id: body.userId,
        tableName: 'AD_User'
      }
    }
  }
  if(body.productId) {
    newObjValue = {...newObjValue, 
      M_Product_ID: {
        id: body.productId,
        tableName: 'M_Product'
      }
    }
  }
  if(body.locationId) {
    newObjValue = {...newObjValue, 
      C_Location_ID: {
        id: body.locationId,
        tableName: 'C_Location'
      }
    }
  }
  if(body.assetGroupId) {
    newObjValue = {...newObjValue, 
      A_Asset_Group_ID: {
        id: body.assetGroupId,
        tableName: 'A_Asset_Group'
      }
    }
  }
  if(body.partnerId) {
    newObjValue = {...newObjValue, 
      C_BPartner_ID: {
        id: body.partnerId,
        tableName: 'C_BPartner'
      }
    }
  }
  if(body.partnerLocationId) {
    newObjValue = {...newObjValue, 
      C_BPartner_Location_ID: {
        id: body.partnerLocationId,
        tableName: 'C_BPartner_Location'
      }
    }
  }
  if(body.attributeSetInstanceId) {
    newObjValue = {...newObjValue, 
      M_AttributeSetInstance_ID: {
        id: body.attributeSetInstanceId,
        tableName: 'M_AttributeSetInstance'
      }
    }
  }
  if(body.projectId) {
    newObjValue = {...newObjValue, 
      C_Project_ID: {
        id: body.projectId,
        tableName: 'C_Project'
      }
    }
  }
  if(body.parentAssetId) {
    newObjValue = {...newObjValue, 
      A_Parent_Asset_ID: {
        id: body.parentAssetId,
        tableName: 'A_Asset'
      }
    }
  }
  if(body.assetStatusId) {
    newObjValue = {...newObjValue, 
      A_Asset_Status: {
        id: body.assetStatusId
      }
    }
  }
  if(body.assetActionId) {
    newObjValue = {...newObjValue, 
      A_Asset_Action: {
        id: body.assetActionId
      }
    }
  }
  if(body.activityId) {
    newObjValue = {...newObjValue, 
      C_Activity_ID: {
        id: body.activityId,
        tableName: 'C_Activity'
      }
    }
  }

  const res: any = await fetchHelper(event, 'models/a_asset', 'POST', token, {
    AD_Org_ID: {
      id: body.organizationId,
      tableName: 'AD_Org'
    },
    isActive: body.isActive,
    name: body.name,
    value: body.value,
    description: body.description,
    help: body.help,
    lot: body.lot,
    isDisposed: body.isDisposed,
    isInPosession: body.isInPosession,
    useLifeYears: body.useLifeYears,
    assetDisposalDate: body.assetDisposalDate,
    isOwned: body.isOwned,
    locationComment: body.locationComment,
    isDepreciated: body.isDepreciated,
    lifeUseUnits: body.lifeUseUnits,
    processing: body.processing,
    guaranteeDate: body.guaranteeDate,
    useLifeMonths: body.useLifeMonths,
    assetServiceDate: body.assetServiceDate,
    useUnits: body.useUnits,
    serNo: body.serNo,
    isFullyDepreciated: body.isFullyDepreciated,
    qty: body.qty,
    lastMaintenanceDate: body.lastMaintenanceDate,
    nextMaintenenceDate: body.nextMaintenenceDate,
    lastMaintenanceUnit: body.lastMaintenanceUnit,
    nextMaintenenceUnit: body.nextMaintenenceUnit,
    lastMaintenanceNote: body.lastMaintenanceNote,
    A_Asset_CreateDate: body.assetCreateDate,
    A_Asset_RevalDate: body.assetRevalDate,
    A_QTY_Current: body.qtyCurrent,
    A_QTY_Original: body.qtyOriginal,
    processed: body.processed,
    assetActivationDate: body.assetActivationDate,
    inventoryNo: body.inventoryNo,
    A_AssetType: body.assetType,
    manufacturedYear: body.manufacturedYear || 1900,
    ...newObjValue,
    tableName: 'A_Asset'
  })
  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) {
      data = errorHandlingHelper(err?.data ?? err, error?.data ?? error)
      forceLogoutHelper(event, data)
    }
  }

  return data
})