import refreshTokenHelper from "../../../utils/refreshTokenHelper"
import forceLogoutHelper from "../../../utils/forceLogoutHelper"
import errorHandlingHelper from "../../../utils/errorHandlingHelper"

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.supervisorId) {
    newObjValue = {...newObjValue, 
      Supervisor_ID: {
        id: body.supervisorId,
        tableName: 'AD_User'
      }
    }
  }
  if(body.partnerId) {
    newObjValue = {...newObjValue, 
      C_BPartner_ID: {
        id: body.partnerId,
        tableName: 'C_BPartner'
      }
    }
  }
  if(body.notificationTypeId) {
    newObjValue = {...newObjValue, 
      NotificationType: {
        id: body.notificationTypeId
      }
    }
  }
  if(body.greetingId) {
    newObjValue = {...newObjValue, 
      C_Greeting_ID: {
        id: body.greetingId,
        tableName: 'C_Greeting'
      }
    }
  }
  if(body.partnerLocationId) {
    newObjValue = {...newObjValue, 
      C_BPartner_Location_ID: {
        id: body.partnerLocationId,
        tableName: 'C_BPartner_Location'
      }
    }
  }
  if(body.orgTrxId) {
    newObjValue = {...newObjValue, 
      AD_OrgTrx_ID: {
        id: body.orgTrxId,
        tableName: 'AD_Org'
      }
    }
  }
  if(body.jobId) {
    newObjValue = {...newObjValue, 
      C_Job_ID: {
        id: body.jobId,
        tableName: 'C_Job'
      }
    }
  }
  if(body.isMenuAutoExpandId) {
    newObjValue = {...newObjValue, 
      IsMenuAutoExpand: {
        id: body.isMenuAutoExpandId
      }
    }
  }
  if(body.mailTextId) {
    newObjValue = {...newObjValue, 
      R_DefaultMailText_ID: {
        id: body.mailTextId,
        tableName: 'R_Mailtext'
      }
    }
  }
  if(body.positionId) {
    newObjValue = {...newObjValue, 
      C_Job_ID: {
        id: body.positionId,
        tableName: 'C_Job'
      }
    }
  }
  if(body.datePasswordChanged) {
    newObjValue = {...newObjValue, 
      datePasswordChanged: body.datePasswordChanged
    }
  }
  if(body.eMailVerifyDate) {
    newObjValue = {...newObjValue, 
      eMailVerifyDate: body.eMailVerifyDate
    }
  }
  if(body.imageId || body.image) {
    newObjValue = {...newObjValue, 
      AD_Image_ID: {
        id: body.imageId,
        data: body.image,
        tableName: 'AD_Image'
      }
    }
  }
  if(body.locationId) {
    newObjValue = {...newObjValue, 
      C_Location_ID: {
        id: body.locationId,
        tableName: 'C_Location'
      }
    }
  }
  if(body.campaignId) {
    newObjValue = {...newObjValue, 
      C_Campaign_ID: {
        id: body.campaignId,
        tableName: 'C_Campaign'
      }
    }
  }
  if(body.leadSourceId) {
    newObjValue = {...newObjValue, 
      LeadSource: {
        id: body.leadSourceId
      }
    }
  }
  if(body.leadStatusId) {
    newObjValue = {...newObjValue, 
      LeadStatus: {
        id: body.leadStatusId
      }
    }
  }
  if(body.leadSourceDescription) {
    newObjValue = {...newObjValue, 
      LeadSourceDescription: body.leadSourceDescription
    }
  }
  if(body.leadStatusDescription) {
    newObjValue = {...newObjValue, 
      LeadStatusDescription: body.leadStatusDescription
    }
  }
  if(body.isSystemUser) {
    newObjValue = {...newObjValue, 
      isSystemUser: body.isSystemUser
    }
  }

  const res: any = await event.context.fetch('models/ad_user/'+body.id, 'PUT', token, {
    isActive: body.isActive,
    name: body.name,
    description: body.description,
    password: body.password,
    eMail: body.eMail,
    isFullBPAccess: body.isFullBPAccess,
    value: body.value,
    isInPayroll: body.isInPayroll,
    isSalesLead: body.isSalesLead,
    isLocked: body.isLocked,
    failedLoginCount: body.failedLoginCount,
    isNoPasswordReset: body.isNoPasswordReset,
    isExpired: body.isExpired,
    isAddMailTextAutomatically: body.isAddMailTextAutomatically,
    isNoExpire: body.isNoExpire,
    isSupportUser: body.isSupportUser,
    isShipTo: body.isShipTo,
    isBillTo: body.isBillTo,
    isVendorLead: body.isVendorLead,
    eMailUser: body.eMailUser,
    phone2: body.phone2,
    birthday: body.birthday,
    phone: body.phone,
    fax: body.fax,
    lastResult: body.lastResult,
    lastContact: body.lastContact,
    title: body.title,
    comments: body.comments,
    companyname: body.companyname,
    URL: body.URL,
    //eMailVerify: body.eMailVerify,
    LDAPUser: body.LDAPUser,
    ...newObjValue,
    tableName: 'AD_User'
  })
  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
})