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.productId) {
    newObjValue = {...newObjValue, 
      M_Product_ID: {
        id: body.productId,
        tableName: 'M_Product'
      }
    }
  }
  if(body.isCreatedId) {
    newObjValue = {...newObjValue, 
      IsCreated: {
        id: body.isCreatedId
      }
    }
  }
  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.locatorId) {
    newObjValue = {...newObjValue, 
      M_Locator_ID: {
        id: body.locatorId,
        tableName: 'M_Locator'
      }
    }
  }
  if(body.docStatusId) {
    newObjValue = {...newObjValue, 
      DocStatus: {
        id: body.docStatusId
      }
    }
  }
  if(body.docTypeId) {
    newObjValue = {...newObjValue, 
      C_DocType_ID: {
        id: body.docTypeId,
        tableName: 'C_DocType'
      }
    }
  }
  if(body.organizationId) {
    newObjValue = {...newObjValue, 
      AD_Org_ID: {
        id: body.organizationId,
        tableName: 'AD_Org'
      }
    }
  }

  const res: any = await fetchHelper(event, 'models/m_production/'+body.id, 'PUT', token, {
    isActive: body.isActive,
    name: body.name,
    description: body.description,
    movementDate: body.movementDate,
    processed: body.processed,
    processedOn: body.processedOn,
    documentNo: body.documentNo,
    productionQty: body.productionQty,
    datePromised: body.datePromised,
    isComplete: body.isComplete,
    isUseProductionPlan: body.isUseProductionPlan,
    ...newObjValue,
    tableName: 'm_production'
  })
  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
})