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 token = authToken ?? await getTokenHelper(event)
  const body = await readBody(event)

  let newObjValue = {}
  if(body.uomId) {
    newObjValue = {...newObjValue, 
      C_UOM_ID: {
        id: body.uomId,
        tableName: 'C_UOM'
      }
    }
  }
  if(body.componentTypeId) {
    newObjValue = {...newObjValue, 
      ComponentType: {
        id: body.componentTypeId
      }
    }
  }
  if(body.issueMethodId) {
    newObjValue = {...newObjValue, 
      IssueMethod: {
        id: body.issueMethodId
      }
    }
  }
  if(body.productId) {
    newObjValue = {...newObjValue, 
      M_Product_ID: {
        id: body.productId
      }
    }
  }
  if(body.organizationId) {
    newObjValue = {...newObjValue, 
      AD_Org_ID: {
        id: body.organizationId,
        tableName: 'AD_Org'
      }
    }
  }

  if(body.id) {
    const res: any = await fetchHelper(event, 'models/pp_product_bomline/'+body.id, 'PUT', token, {
      isActive: body.isActive,
      line: body.line,
      scrap: body.scrap,
      qtyBatch: body.qtyBatch,
      qtyBOM: body.qtyBOM,
      validFrom: body.validFrom,
      leadTimeOffset: body.leadTimeOffset,
      isQtyPercentage: body.isQtyPercentage,
      isCritical: body.isCritical,
      forecast: body.forecast,  
      description: body.description,
      assay: body.assay,
      ...newObjValue,
      tableName: 'pp_product_bomline'
    })
    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
})