/* eslint-disable @typescript-eslint/no-unused-vars */
/**
 * Session Replay Repository — Remote Diagnostics
 * Ingest and query session replay events.
 */

import { getCollection } from '../../lib/datastore.js';
import type { SessionReplayDoc, ReplayEvent, QueryReplayInput } from './session-replay-types.js';

const REPLAY_CONTAINER = 'session_replays';

function replaysCollection() {
  return getCollection<SessionReplayDoc>(REPLAY_CONTAINER, '/pk');
}

/**
 * Ingest replay events for a session.
 */
export async function ingestReplayEvents(
  productId: string,
  sessionId: string,
  events: ReplayEvent[],
  privacyConfig: SessionReplayDoc['privacyConfig']
): Promise<{ accepted: number }> {
  const collection = replaysCollection();

  // Build or update session replay document
  const pk = `${productId}:${sessionId}`;
  const existing = await collection.findMany({
    filter: { pk, sessionId },
    limit: 1,
  });

  const now = new Date().toISOString();

  if (existing.length > 0) {
    // Append events to existing document
    const doc = existing[0];
    const updatedEvents = [...doc.events, ...events];

    await collection.upsert({
      ...doc,
      events: updatedEvents,
      eventCount: updatedEvents.length,
      durationMs: events[events.length - 1]?.timestamp || doc.durationMs,
      updatedAt: now,
    });
  } else {
    // Create new replay document
    const firstEvent = events[0];
    const lastEvent = events[events.length - 1];

    const doc: SessionReplayDoc = {
      id: `replay_${sessionId}`,
      pk,
      sessionId,
      productId,
      events,
      eventCount: events.length,
      startTimestamp: now,
      endTimestamp: now,
      durationMs: lastEvent?.timestamp || 0,
      privacyConfig,
      createdAt: now,
      updatedAt: now,
      ttl: 7 * 86400, // 7 days
    };

    await collection.upsert(doc);
  }

  return { accepted: events.length };
}

/**
 * Get replay events for a session.
 */
export async function getSessionReplay(
  productId: string,
  sessionId: string
): Promise<SessionReplayDoc | null> {
  const collection = replaysCollection();
  const pk = `${productId}:${sessionId}`;

  const results = await collection.findMany({
    filter: { pk, sessionId },
    limit: 1,
  });

  return results[0] ?? null;
}

/**
 * Query replay events with pagination.
 */
export async function queryReplayEvents(
  productId: string,
  sessionId: string,
  query: QueryReplayInput
): Promise<{
  events: ReplayEvent[];
  totalEvents: number;
  continuationToken?: string;
}> {
  const replay = await getSessionReplay(productId, sessionId);

  if (!replay) {
    return { events: [], totalEvents: 0 };
  }

  // Simple pagination based on event index
  const allEvents = replay.events;
  const totalEvents = allEvents.length;

  let startIndex = 0;
  if (query.continuationToken) {
    startIndex = parseInt(query.continuationToken, 10);
    if (isNaN(startIndex)) startIndex = 0;
  }

  const endIndex = Math.min(startIndex + query.limit, totalEvents);
  const events = allEvents.slice(startIndex, endIndex);

  const nextContinuationToken = endIndex < totalEvents ? String(endIndex) : undefined;

  return {
    events,
    totalEvents,
    continuationToken: nextContinuationToken,
  };
}

/**
 * Delete session replay data.
 */
export async function deleteSessionReplay(productId: string, sessionId: string): Promise<boolean> {
  const collection = replaysCollection();
  const pk = `${productId}:${sessionId}`;

  const results = await collection.findMany({
    filter: { pk, sessionId },
    limit: 1,
  });

  if (results.length === 0) return false;

  // Soft delete - update with empty events
  await collection.upsert({
    ...results[0],
    events: [],
    eventCount: 0,
    durationMs: 0,
    updatedAt: new Date().toISOString(),
  });

  return true;
}
