/**
 * Metrics dashboard endpoints
 */

import { FastifyInstance } from 'fastify';
import { getCredentialMetrics, getMetricsDashboard } from './metrics';
import { searchAuditLogs, exportAuditLogs } from '@the-order/database';
import { authenticateJWT, requireRole } from '@the-order/shared';

export async function registerMetricsRoutes(server: FastifyInstance): Promise<void> {
  // Get credential metrics
  server.get(
    '/metrics',
    {
      preHandler: [authenticateJWT, requireRole('admin', 'monitor')],
      schema: {
        querystring: {
          type: 'object',
          properties: {
            startDate: { type: 'string', format: 'date-time' },
            endDate: { type: 'string', format: 'date-time' },
          },
        },
        description: 'Get credential issuance metrics',
        tags: ['metrics'],
      },
    },
    async (request, reply) => {
      const { startDate, endDate } = request.query as {
        startDate?: string;
        endDate?: string;
      };

      const metrics = await getCredentialMetrics(
        startDate ? new Date(startDate) : undefined,
        endDate ? new Date(endDate) : undefined
      );

      return reply.send(metrics);
    }
  );

  // Get metrics dashboard
  server.get(
    '/metrics/dashboard',
    {
      preHandler: [authenticateJWT, requireRole('admin', 'monitor')],
      schema: {
        description: 'Get metrics dashboard data',
        tags: ['metrics'],
      },
    },
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    async (_request: any, reply: any) => {
      const dashboard = await getMetricsDashboard();
      return reply.send(dashboard);
    }
  );

  // Search audit logs
  server.post(
    '/metrics/audit/search',
    {
      preHandler: [authenticateJWT, requireRole('admin', 'auditor')],
      schema: {
        body: {
          type: 'object',
          properties: {
            credentialId: { type: 'string' },
            issuerDid: { type: 'string' },
            subjectDid: { type: 'string' },
            credentialType: { type: 'array', items: { type: 'string' } },
            action: { type: 'string', enum: ['issued', 'revoked', 'verified', 'renewed'] },
            performedBy: { type: 'string' },
            startDate: { type: 'string', format: 'date-time' },
            endDate: { type: 'string', format: 'date-time' },
            ipAddress: { type: 'string' },
            page: { type: 'number' },
            pageSize: { type: 'number' },
          },
        },
        description: 'Search audit logs',
        tags: ['metrics'],
      },
    },
    async (request, reply) => {
      const body = request.body as {
        credentialId?: string;
        issuerDid?: string;
        subjectDid?: string;
        credentialType?: string | string[];
        action?: 'issued' | 'revoked' | 'verified' | 'renewed';
        performedBy?: string;
        startDate?: string;
        endDate?: string;
        ipAddress?: string;
        page?: number;
        pageSize?: number;
      };

      const result = await searchAuditLogs(
        {
          credentialId: body.credentialId,
          issuerDid: body.issuerDid,
          subjectDid: body.subjectDid,
          credentialType: body.credentialType,
          action: body.action,
          performedBy: body.performedBy,
          startDate: body.startDate ? new Date(body.startDate) : undefined,
          endDate: body.endDate ? new Date(body.endDate) : undefined,
          ipAddress: body.ipAddress,
        },
        body.page || 1,
        body.pageSize || 50
      );

      return reply.send(result);
    }
  );

  // Export audit logs
  server.post(
    '/metrics/audit/export',
    {
      preHandler: [authenticateJWT, requireRole('admin', 'auditor')],
      schema: {
        body: {
          type: 'object',
          properties: {
            credentialId: { type: 'string' },
            issuerDid: { type: 'string' },
            subjectDid: { type: 'string' },
            credentialType: { type: 'array', items: { type: 'string' } },
            action: { type: 'string', enum: ['issued', 'revoked', 'verified', 'renewed'] },
            startDate: { type: 'string', format: 'date-time' },
            endDate: { type: 'string', format: 'date-time' },
            format: { type: 'string', enum: ['json', 'csv'] },
          },
        },
        description: 'Export audit logs',
        tags: ['metrics'],
      },
    },
    async (request, reply) => {
      const body = request.body as {
        credentialId?: string;
        issuerDid?: string;
        subjectDid?: string;
        credentialType?: string | string[];
        action?: 'issued' | 'revoked' | 'verified' | 'renewed';
        startDate?: string;
        endDate?: string;
        format?: 'json' | 'csv';
      };

      const exported = await exportAuditLogs(
        {
          credentialId: body.credentialId,
          issuerDid: body.issuerDid,
          subjectDid: body.subjectDid,
          credentialType: body.credentialType,
          action: body.action,
          startDate: body.startDate ? new Date(body.startDate) : undefined,
          endDate: body.endDate ? new Date(body.endDate) : undefined,
        },
        body.format || 'json'
      );

      const contentType = body.format === 'csv' ? 'text/csv' : 'application/json';
      return reply.type(contentType).send(exported);
    }
  );
}

