/**
 * In-memory event store implementation.
 * Useful for development, testing, and as a fallback when no persistent backend is configured.
 * Caps at maxEvents to prevent unbounded memory growth.
 */

import type { EventStore, StoredEvent, EventStoreQuery } from './types.js';

export interface MemoryStoreOptions {
  maxEvents?: number;
}

export class MemoryEventStore implements EventStore {
  private events: StoredEvent[] = [];
  private readonly maxEvents: number;

  constructor(options?: MemoryStoreOptions) {
    this.maxEvents = options?.maxEvents ?? 10_000;
  }

  async append(event: StoredEvent): Promise<void> {
    this.events.push(event);
    if (this.events.length > this.maxEvents) {
      this.events = this.events.slice(-this.maxEvents);
    }
  }

  async query(q: EventStoreQuery): Promise<StoredEvent[]> {
    let results = this.events;

    if (q.userId) results = results.filter(e => e.userId === q.userId);
    if (q.type) results = results.filter(e => e.type === q.type);
    if (q.after) results = results.filter(e => e.timestamp > q.after!);
    if (q.before) results = results.filter(e => e.timestamp < q.before!);

    if (q.limit && q.limit > 0) {
      results = results.slice(-q.limit);
    }

    return results;
  }

  async recent(limit = 50): Promise<StoredEvent[]> {
    return this.events.slice(-limit);
  }

  async count(): Promise<number> {
    return this.events.length;
  }

  async clear(): Promise<void> {
    this.events = [];
  }
}
