import type { ParsedQuery } from '../data-sources/types'

type PostgrestOperator = 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'like' | 'ilike'

export function applyParsedQuery(builder: any, parsed: ParsedQuery | null) {
  if (!parsed) {
    return builder
  }

  for (const filter of parsed.filters) {
    const operator: PostgrestOperator = (filter.operator ?? 'eq') as PostgrestOperator

    if (typeof builder[operator] === 'function') {
      const value = operator === 'like' || operator === 'ilike' ? String(filter.value) : filter.value
      builder = builder[operator](filter.field, value)
    }
  }

  if (parsed.orderBy && typeof builder.order === 'function') {
    builder = builder.order(parsed.orderBy.field, {
      ascending: parsed.orderBy.ascending !== false
    })
  }

  if (parsed.limit && parsed.offset !== undefined && typeof builder.range === 'function') {
    const from = parsed.offset
    const to = parsed.offset + parsed.limit - 1
    builder = builder.range(from, to)
  } else if (parsed.limit && typeof builder.limit === 'function') {
    builder = builder.limit(parsed.limit)
  }

  return builder
}
