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.currencyId) {
    newObjValue = {...newObjValue, 
      C_Currency_ID: {
        id: body.currencyId,
        tableName: 'C_Currency'
      }
    }
  }
  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.salesRepId) {
    newObjValue = {...newObjValue, 
      SalesRep_ID: {
        id: body.salesRepId,
        tableName: 'AD_User'
      }
    }
  }
  if(body.priceListVersionId) {
    newObjValue = {...newObjValue, 
      M_PriceList_Version_ID: {
        id: body.priceListVersionId,
        tableName: 'M_PriceList_Version'
      }
    }
  }
  if(body.campaignId) {
    newObjValue = {...newObjValue, 
      C_Campaign_ID: {
        id: body.campaignId,
        tableName: 'C_Campaign'
      }
    }
  }
  if(body.paymentTermId) {
    newObjValue = {...newObjValue, 
      C_PaymentTerm_ID: {
        id: body.paymentTermId,
        tableName: 'C_PaymentTerm'
      }
    }
  }
  if(body.userId) {
    newObjValue = {...newObjValue, 
      AD_User_ID: {
        id: body.userId,
        tableName: 'AD_User'
      }
    }
  }
  if(body.warehouseId) {
    newObjValue = {...newObjValue, 
      M_Warehouse_ID: {
        id: body.warehouseId,
        tableName: 'M_Warehouse'
      }
    }
  }
  if(body.projectCategoryId) {
    newObjValue = {...newObjValue, 
      ProjectCategory: {
        id: body.projectCategoryId
      }
    }
  }
  if(body.projInvoiceRuleId) {
    newObjValue = {...newObjValue, 
      ProjInvoiceRule: {
        id: body.projInvoiceRuleId
      }
    }
  }
  if(body.projectLineLevelId) {
    newObjValue = {...newObjValue, 
      ProjectLineLevel: {
        id: body.projectLineLevelId
      }
    }
  }
  if(body.partnerSRId) {
    newObjValue = {...newObjValue, 
      C_BPartnerSR_ID: {
        id: body.partnerSRId,
        tableName: 'C_BPartner'
      }
    }
  }
  if(body.paymentTermId) {
    newObjValue = {...newObjValue, 
      C_PaymentTerm_ID: {
        id: body.paymentTermId,
        tableName: 'C_PaymentTerm'
      }
    }
  }
  if(body.organizationId) {
    newObjValue = {...newObjValue, 
      AD_Org_ID: {
        id: body.organizationId,
        tableName: 'AD_Org'
      }
    }
  }
  if(!body.isSummary) {
    newObjValue = {...newObjValue, 
      committedAmt: body.committedAmt,
      dateContract: body.dateContract,
      dateFinish: body.dateFinish,
      processed: body.processed,
      plannedAmt: body.plannedAmt,
      plannedQty: body.plannedQty,
      plannedMarginAmt: body.plannedMarginAmt,
      invoicedAmt: body.invoicedAmt,
      invoicedQty: body.invoicedQty,
      projectBalanceAmt: body.projectBalanceAmt,
      committedQty: body.committedQty,
      POReference: body.poReference,
    }
  }

  const res: any = await fetchHelper(event, 'models/c_project/'+body.id, 'PUT', token, {
    isActive: body.isActive,
    name: body.name,
    value: body.value,
    description: body.description,
    note: body.note,
    isSummary: body.isSummary,
    isCommitment: body.isCommitment,
    isCommitCeiling: body.isCommitCeiling,
    ...newObjValue,
    tableName: 'C_Project'
  })
  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
})