import { getCollection } from './datastore.js';

interface StoredEvent {
  id: string;
  productId: string;
  topic: string;
  payload: Record<string, unknown>;
  source?: string;
  createdAt: string;
  _ts?: number;
}

function eventLogCollection() {
  return getCollection<StoredEvent>('event_log', '/productId');
}

export async function storeEvent(
  productId: string,
  topic: string,
  payload: Record<string, unknown>,
  eventId: string,
  source?: string
): Promise<StoredEvent> {
  const doc: StoredEvent = {
    id: eventId,
    productId,
    topic,
    payload,
    source,
    createdAt: new Date().toISOString(),
  };
  return eventLogCollection().create(doc);
}

export async function listEvents(
  productId: string,
  options: { topic?: string; since?: string; until?: string; limit?: number }
): Promise<StoredEvent[]> {
  const events = await eventLogCollection().findMany({
    filter: {
      productId,
      ...(options.topic ? { topic: options.topic } : {}),
    },
    sort: { createdAt: -1 },
    limit: options.limit ?? 100,
  });

  // Filter by time range in-memory (Cosmos SDK filter limitations)
  return events.filter(e => {
    if (options.since && e.createdAt < options.since) return false;
    if (options.until && e.createdAt > options.until) return false;
    return true;
  });
}
