import { FastifyPluginAsync } from 'fastify';
import { PriceRepository } from '../../database/repository';

const repository = new PriceRepository();

export const indexRoutes: FastifyPluginAsync = async (server) => {
  // GET /api/index/history?range=7d|30d|90d|all
  server.get<{
    Querystring: { range?: string };
  }>('/history', async (request, reply) => {
    try {
      const { range = '7d' } = request.query;
      const history = await repository.getIndexHistory(range);

      return {
        success: true,
        data: history.map((h: any) => ({
          timestamp: h.timestamp,
          price: h.lowestPrice.toString(),
          vendor: h.vendor,
          seller: h.sellerName,
        })),
      };
    } catch (error) {
      reply.code(500);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  });

  // WebSocket endpoint for real-time updates
  server.get('/ws', { websocket: true }, (connection: any, request: any) => {
    connection.socket.on('message', (message: any) => {
      // Echo back for now - will be replaced with real-time updates
      connection.socket.send(message.toString());
    });

    // Send initial data
    repository.getLowestPrice().then(lowest => {
      if (lowest) {
        connection.socket.send(JSON.stringify({
          type: 'index',
          data: {
            timestamp: lowest.timestamp,
            price: lowest.lowestPrice.toString(),
            vendor: lowest.vendor,
            seller: lowest.sellerName,
          },
        }));
      }
    });
  });
};
