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.tableId) {
    newObjValue = {...newObjValue, 
      AD_Table_ID: {
        id: body.tableId,
        tableName: 'AD_Table'
      }
    }
  }
  if(body.formId) {
    newObjValue = {...newObjValue, 
      AD_Form_ID: {
        id: body.formId,
        tableName: 'AD_Form'
      }
    }
  }
  if(body.entityTypeId) {
    newObjValue = {...newObjValue, 
      EntityType: {
        id: body.entityTypeId,
        tableName: 'AD_EntityType'
      }
    }
  }
  if(body.windowId) {
    newObjValue = {...newObjValue, 
      AD_Window_ID: {
        id: body.windowId,
        tableName: 'AD_Window'
      }
    }
  }
  if(body.namePrintColorId) {
    newObjValue = {...newObjValue, 
      Name_PrintColor_ID: {
        id: body.namePrintColorId,
        tableName: 'AD_PrintColor'
      }
    }
  }
  if(body.numberPrintColorId) {
    newObjValue = {...newObjValue, 
      Number_PrintColor_ID: {
        id: body.numberPrintColorId,
        tableName: 'AD_PrintColor'
      }
    }
  }
  if(body.projectId) {
    newObjValue = {...newObjValue, 
      C_Project_ID: {
        id: body.projectId,
        tableName: 'C_Project'
      }
    }
  }
  if(body.namePrintFontId) {
    newObjValue = {...newObjValue, 
      Name_PrintFont_ID: {
        id: body.namePrintFontId,
        tableName: 'AD_PrintFont'
      }
    }
  }
  if(body.numberPrintFontId) {
    newObjValue = {...newObjValue, 
      Number_PrintFont_ID: {
        id: body.numberPrintFontId,
        tableName: 'AD_PrintFont'
      }
    }
  }
  if(body.organizationId) {
    newObjValue = {...newObjValue, 
      AD_Org_ID: {
        id: body.organizationId,
        tableName: 'AD_Org'
      }
    }
  }

  const res: any = await fetchHelper(event, 'models/pa_documentstatus/'+body.id, 'PUT', token, {
    isActive: body.isActive,
    name: body.name,
    description: body.description,
    seqNo: body.seqNo,
    whereClause: body.whereClause,
    ...newObjValue,
    tableName: 'pa_documentstatus'
  })
  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
})