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

const repository = new PriceRepository();

export const priceRoutes: FastifyPluginAsync = async (server) => {
  // GET /api/prices/latest - Get all current listings with lowest price
  server.get('/latest', async (request, reply) => {
    try {
      const prices = await repository.getLatestPrices();
      
      if (prices.length === 0) {
        return {
          success: true,
          data: {
            timestamp: new Date(),
            lowestPrice: 0,
            platform: '',
            sellerName: '',
            allPrices: []
          }
        };
      }

      const lowestPrice = prices.reduce((min: any, p: any) => 
        Number(p.usdPerMillion) < Number(min.usdPerMillion) ? p : min
      );

      return {
        success: true,
        data: {
          timestamp: new Date(),
          lowestPrice: Number(lowestPrice.usdPerMillion),
          platform: lowestPrice.vendor,
          sellerName: lowestPrice.sellerName,
          allPrices: prices.map((p: any) => ({
            id: p.id,
            platform: p.vendor,
            sellerName: p.sellerName,
            pricePerMillion: Number(p.usdPerMillion),
            timestamp: p.timestamp,
            url: p.url
          }))
        }
      };
    } catch (error) {
      reply.code(500);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  });

  // GET /api/prices/lowest - Get current lowest price
  server.get('/lowest', async (request, reply) => {
    try {
      const lowest = await repository.getLowestPrice();
      if (!lowest) {
        return { success: true, data: null };
      }
      return {
        success: true,
        data: {
          timestamp: lowest.timestamp,
          price: lowest.lowestPrice.toString(),
          vendor: lowest.vendor,
          seller: lowest.sellerName,
        },
      };
    } catch (error) {
      reply.code(500);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  });

  // GET /api/prices/by-seller?seller=&platform=
  server.get<{
    Querystring: { seller: string; platform?: string };
  }>('/by-seller', async (request, reply) => {
    try {
      const { seller, platform } = request.query;
      if (!seller) {
        reply.code(400);
        return { success: false, error: 'seller parameter is required' };
      }

      const prices = await repository.getPricesBySeller(seller, platform);
      return {
        success: true,
        data: prices.map((p: any) => ({
          timestamp: p.timestamp,
          vendor: p.vendor,
          seller: p.sellerName,
          usdPerMillion: p.usdPerMillion.toString(),
          deliveryTime: p.deliveryTime,
        })),
      };
    } catch (error) {
      reply.code(500);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  });

  // GET /api/prices/by-platform?platform=
  server.get<{
    Querystring: { platform: string };
  }>('/by-platform', async (request, reply) => {
    try {
      const { platform } = request.query;
      if (!platform) {
        reply.code(400);
        return { success: false, error: 'platform parameter is required' };
      }

      const prices = await repository.getPricesByPlatform(platform);
      return {
        success: true,
        data: prices.map((p: any) => ({
          timestamp: p.timestamp,
          seller: p.sellerName,
          usdPerMillion: p.usdPerMillion.toString(),
          deliveryTime: p.deliveryTime,
        })),
      };
    } catch (error) {
      reply.code(500);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  });

  // GET /api/prices/history?from=&to=&seller=&platform=
  server.get<{
    Querystring: { from: string; to: string; seller?: string; platform?: string };
  }>('/history', async (request, reply) => {
    try {
      const { from, to, seller, platform } = request.query;
      if (!from || !to) {
        reply.code(400);
        return { success: false, error: 'from and to parameters are required' };
      }

      const fromDate = new Date(from);
      const toDate = new Date(to);

      if (isNaN(fromDate.getTime()) || isNaN(toDate.getTime())) {
        reply.code(400);
        return { success: false, error: 'Invalid date format' };
      }

      const prices = await repository.getPriceHistory(fromDate, toDate, seller, platform);
      return {
        success: true,
        data: prices.map((p: any) => ({
          timestamp: p.timestamp,
          vendor: p.vendor,
          seller: p.sellerName,
          usdPerMillion: p.usdPerMillion.toString(),
          deliveryTime: p.deliveryTime,
        })),
      };
    } catch (error) {
      reply.code(500);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  });
};
