import { EldoradoScraper } from './eldorado-scraper';
import { PlayerAuctionsScraper } from './playerauctions-scraper';
import { ScrapeResult, VendorListing } from './types';

export class ScraperService {
  private eldoradoScraper: EldoradoScraper;
  private playerAuctionsScraper: PlayerAuctionsScraper;

  constructor() {
    this.eldoradoScraper = new EldoradoScraper();
    this.playerAuctionsScraper = new PlayerAuctionsScraper();
  }

  async scrapeAll(): Promise<ScrapeResult[]> {
    const results = await Promise.allSettled([
      this.eldoradoScraper.scrape(),
      this.playerAuctionsScraper.scrape(),
    ]);

    return results.map((result, index) => {
      if (result.status === 'fulfilled') {
        return result.value;
      } else {
        const vendor = index === 0 ? 'eldorado' : 'playerauctions';
        return {
          success: false,
          vendor,
          listings: [],
          error: result.reason?.message || 'Unknown error',
          scrapedAt: new Date(),
        };
      }
    });
  }

  async scrapeEldorado(): Promise<ScrapeResult> {
    return this.eldoradoScraper.scrape();
  }

  async scrapePlayerAuctions(): Promise<ScrapeResult> {
    return this.playerAuctionsScraper.scrape();
  }

  calculatePriceIndex(listings: VendorListing[]): number | null {
    if (listings.length === 0) return null;

    const prices = listings.map(l => l.pricePerMillion);
    
    // Return the lowest price
    return Math.min(...prices);
  }

  async close(): Promise<void> {
    await Promise.all([
      this.eldoradoScraper.close(),
      this.playerAuctionsScraper.close(),
    ]);
  }
}
