import { FastifyInstance, FastifyPluginOptions } from 'fastify';
import type { AnalyticsEngine } from '../modules/analytics/index.js';

interface AnalyticsRouteOpts extends FastifyPluginOptions {
  analyticsEngine: AnalyticsEngine;
}

export default async function analyticsRoutes(app: FastifyInstance, opts: AnalyticsRouteOpts) {
  const { analyticsEngine } = opts;

  // GET /analytics/characters/:id — Character analytics
  app.get('/analytics/characters/:id', async (request, reply) => {
    const { id } = request.params as { id: string };
    const { period, startDate, endDate } = request.query as {
      period?: 'daily' | 'weekly' | 'monthly';
      startDate?: string;
      endDate?: string;
    };

    try {
      const analytics = await analyticsEngine.getCharacterAnalytics(
        id,
        period || 'daily',
        startDate,
      );
      return reply.status(200).send({ success: true, data: analytics });
    } catch (err: any) {
      return reply.status(500).send({ success: false, error: err.message });
    }
  });

  // GET /analytics/comparison — Character comparison
  app.get('/analytics/comparison', async (request, reply) => {
    const { characterIds, period } = request.query as {
      characterIds?: string;
      period?: 'daily' | 'weekly' | 'monthly';
    };

    try {
      const ids = characterIds ? characterIds.split(',') : [];
      if (ids.length === 0) {
        return reply.status(400).send({ success: false, error: 'characterIds query parameter is required (comma-separated)' });
      }
      const comparison = await analyticsEngine.compareCharacters(ids, period || 'daily');
      return reply.status(200).send({ success: true, data: comparison });
    } catch (err: any) {
      return reply.status(500).send({ success: false, error: err.message });
    }
  });

  // GET /analytics/overview — System overview
  app.get('/analytics/overview', async (_request, reply) => {
    try {
      const overview = await analyticsEngine.getSystemOverview();
      return reply.status(200).send({ success: true, data: overview });
    } catch (err: any) {
      return reply.status(500).send({ success: false, error: err.message });
    }
  });
}
