import { Lead, SearchQuery } from '../types';
import { LeadProvider, calculateQualityScore } from './LeadProvider';

interface FoursquarePlace {
  fsq_id: string;
  name: string;
  location?: {
    formatted_address?: string;
  };
  categories?: { name: string }[];
  tel?: string;
  website?: string;
  email?: string;
}

export class FoursquareProvider implements LeadProvider {
  name = 'Foursquare';
  private apiKey: string;

  constructor() {
    this.apiKey = process.env.FOURSQUARE_API_KEY || '';
  }

  async search(query: SearchQuery): Promise<Lead[]> {
    if (!this.apiKey) {
      console.warn('Foursquare API key not found. Skipping Foursquare search.');
      return [];
    }

    try {
      const limit = query.limit || 50;
      const url = new URL('https://api.foursquare.com/v3/places/search');
      url.searchParams.append('query', query.keyword);
      url.searchParams.append('near', query.location);
      url.searchParams.append('limit', limit.toString());
      url.searchParams.append('fields', 'fsq_id,name,location,categories,tel,website,email');

      const response = await fetch(url.toString(), {
        headers: {
          Accept: 'application/json',
          Authorization: this.apiKey,
        },
      });

      if (!response.ok) {
        throw new Error(`Foursquare API error: ${response.status} ${response.statusText}`);
      }

      const data = await response.json();
      const places: FoursquarePlace[] = data.results || [];

      return places.map((place) => {
        const partial: Partial<Lead> = {
          id: place.fsq_id,
          name: place.name,
          category: place.categories?.[0]?.name || 'Unknown',
          phone: place.tel || '',
          website: place.website || '',
          email: place.email || '',
          address: place.location?.formatted_address || '',
        };

        return {
          ...partial,
          source: this.name,
          qualityScore: calculateQualityScore(partial),
        } as Lead;
      });
    } catch (error) {
      console.error('Error fetching leads from Foursquare:', error);
      return [];
    }
  }
}
