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

import type { FastifyInstance } from 'fastify';
import { requireRole } from '../../lib/auth.js';
import { IngestReplayEventsSchema, QueryReplaySchema } from './session-replay-types.js';
import {
  ingestReplayEvents,
  getSessionReplay,
  queryReplayEvents,
} from './session-replay-repository.js';
import { getRequestProductId } from '../../lib/request-context.js';
import { NotFoundError, BadRequestError } from '../../lib/errors.js';

export async function sessionReplayRoutes(app: FastifyInstance): Promise<void> {
  // Ingest replay events (client endpoint)
  app.post('/diagnostics/sessions/:id/replay', async (req, reply) => {
    const { id: sessionId } = req.params as { id: string };
    const productId = getRequestProductId(req);
    const deviceId = req.headers['x-device-id'] as string | undefined;

    // Require authentication
    if (!req.jwtPayload?.sub) {
      return reply.status(401).send({ error: 'Authentication required' });
    }

    // Validate request body
    const result = IngestReplayEventsSchema.safeParse(req.body);
    if (!result.success) {
      return reply.status(400).send({
        error: 'Invalid replay events',
        details: result.error.issues,
      });
    }

    const { events, privacyConfig } = result.data;

    // Validate session ID matches
    if (result.data.sessionId !== sessionId) {
      throw new BadRequestError('Session ID mismatch');
    }

    // Ingest events
    const ingestResult = await ingestReplayEvents(productId, sessionId, events, privacyConfig);

    app.log.info(`Ingested ${ingestResult.accepted} replay events for session ${sessionId}`);

    return {
      accepted: ingestResult.accepted,
      sessionId,
    };
  });

  // Get full session replay (admin only)
  app.get('/diagnostics/sessions/:id/replay', async (req, reply) => {
    await requireRole(req, 'admin');

    const { id: sessionId } = req.params as { id: string };
    const productId = getRequestProductId(req);

    const replay = await getSessionReplay(productId, sessionId);
    if (!replay) {
      throw new NotFoundError('Session replay not found');
    }

    return {
      sessionId: replay.sessionId,
      eventCount: replay.eventCount,
      durationMs: replay.durationMs,
      events: replay.events,
      privacyConfig: replay.privacyConfig,
    };
  });

  // Query replay events with pagination (admin only)
  app.get('/diagnostics/sessions/:id/replay/events', async (req, reply) => {
    await requireRole(req, 'admin');

    const { id: sessionId } = req.params as { id: string };
    const productId = getRequestProductId(req);
    const query = QueryReplaySchema.parse(req.query);

    const result = await queryReplayEvents(productId, sessionId, query);

    return {
      events: result.events,
      totalEvents: result.totalEvents,
      continuationToken: result.continuationToken,
    };
  });
}
