import type { FilterMap } from '@bytelyst/datastore';
import { getCollection } from '../../lib/datastore.js';
import type { ListTimelineQuery, TimelineItemDoc } from './types.js';

function collection() {
  return getCollection<TimelineItemDoc>('timeline_items', '/productId');
}

export async function upsertTimelineItems(items: TimelineItemDoc[]): Promise<TimelineItemDoc[]> {
  const results: TimelineItemDoc[] = [];
  for (const item of items) {
    results.push(await collection().upsert(item));
  }
  return results;
}

export async function listTimelineItems(
  productId: string,
  query: ListTimelineQuery
): Promise<TimelineItemDoc[]> {
  const filter: FilterMap = { productId };

  if (query.userId) filter.userId = query.userId;
  if (query.correlationId) filter.correlationId = query.correlationId;
  if (query.artifactId) filter.artifactId = query.artifactId;
  if (query.eventName) filter.eventName = query.eventName;

  return collection().findMany({
    filter,
    sort: { occurredAt: -1 },
    limit: query.limit,
  });
}
