import { EventsFilter } from './index'

export const buildWhereQuery = (filter: EventsFilter) => {
  let where: any = {}
  const whereAnd: any = []

  if (filter.marketIds) {
    whereAnd.push({ marketId_in: filter.marketIds })
  }
  if (filter.futureIds) {
    whereAnd.push({ futureId_in: filter.futureIds })
  }
  if (filter.timestampFrom) {
    whereAnd.push({ blockTimestamp_gte: filter.timestampFrom })
  }
  if (filter.timestampTo) {
    whereAnd.push({ blockTimestamp_lte: filter.timestampTo })
  }

  if (filter.userAddress) {
    where.or = [{ owner: filter.userAddress }, { initiator: filter.userAddress }]
    if (Object.keys(whereAnd).length > 0) {
      where.and = whereAnd
    }
  } else {
    where.and = whereAnd
  }
  return JSON.stringify(where).replace(/"([^(")"]+)":/g, '$1:')
}
