/**
 * Symbol routes for HTTP API
 *
 * Provides REST endpoints for symbol search and resolution.
 */

import type { FastifyInstance } from 'fastify';
import type { SymbolIndexService } from '../services/symbol-index-service.js';

export interface SymbolRoutesConfig {
  getSymbolIndexService: () => SymbolIndexService | undefined;
}

export class SymbolRoutes {
  private getSymbolIndexService: () => SymbolIndexService | undefined;

  constructor(config: SymbolRoutesConfig) {
    this.getSymbolIndexService = config.getSymbolIndexService;
  }

  /**
   * Register symbol routes with Fastify
   */
  register(app: FastifyInstance): void {
    // Search symbols
    app.get('/symbols/search', async (request, reply) => {
      const symbolIndexService = this.getSymbolIndexService();

      if (!symbolIndexService) {
        return reply.code(503).send({
          error: 'Symbol index service not ready',
          message: 'Service is still initializing, please try again in a moment',
        });
      }

      const { q, limit } = request.query as { q?: string; limit?: string };

      if (!q) {
        return reply.code(400).send({
          error: 'Query parameter "q" is required',
        });
      }

      const limitNum = limit ? parseInt(limit, 10) : 30;

      try {
        const results = symbolIndexService.search(q, limitNum);
        return { results };
      } catch (error: any) {
        app.log.error({ error: error.message }, 'Symbol search failed');
        return reply.code(500).send({
          error: 'Symbol search failed',
          message: error.message,
        });
      }
    });

    // Resolve symbol (use wildcard to capture ticker with slashes like BTC/USDT.BINANCE)
    app.get('/symbols/*', async (request, reply) => {
      const symbolIndexService = this.getSymbolIndexService();

      if (!symbolIndexService) {
        return reply.code(503).send({
          error: 'Symbol index service not ready',
          message: 'Service is still initializing, please try again in a moment',
        });
      }

      // Extract ticker from wildcard path (everything after /symbols/)
      const ticker = (request.params as any)['*'];

      try {
        const symbolInfo = symbolIndexService.resolveSymbol(ticker);

        if (!symbolInfo) {
          return reply.code(404).send({
            error: 'Symbol not found',
            ticker,
          });
        }

        return symbolInfo;
      } catch (error: any) {
        app.log.error({ error: error.message, ticker }, 'Symbol resolution failed');
        return reply.code(500).send({
          error: 'Symbol resolution failed',
          message: error.message,
        });
      }
    });

    // Get symbol index stats
    app.get('/symbols/stats', async (_request, reply) => {
      const symbolIndexService = this.getSymbolIndexService();

      if (!symbolIndexService) {
        return reply.code(503).send({
          error: 'Symbol index service not ready',
          message: 'Service is still initializing, please try again in a moment',
        });
      }

      try {
        const stats = symbolIndexService.getStats();
        return stats;
      } catch (error: any) {
        app.log.error({ error: error.message }, 'Failed to get symbol stats');
        return reply.code(500).send({
          error: 'Failed to get symbol stats',
          message: error.message,
        });
      }
    });
  }
}
