import { ILeadSource, NormalizedLead, SearchParams, SourceCategory } from "./types";
import { z } from "zod";
import { getApiKey } from "../settings";

export class FoursquareSource implements ILeadSource {
  id = "foursquare";
  name = "Foursquare";
  description = "Local business search focused on high-quality venue data, categories, and contact info.";
  category: SourceCategory = "maps";

  inputSchema = z.object({
    keyword: z.string().min(1, "Search keyword is required"),
    location: z.string().min(1, "Location is required"),
    limit: z.number().optional().default(50),
  });

  async run(params: SearchParams): Promise<NormalizedLead[]> {
    const apiKey = await getApiKey('foursquare');
    if (!apiKey) {
      throw new Error("Foursquare API key is missing. Please set FOURSQUARE_API_KEY in your settings.");
    }

    try {
      const limit = params.limit || 50;
      const url = new URL("https://api.foursquare.com/v3/places/search");
      url.searchParams.append("query", params.keyword || "");
      url.searchParams.append("near", params.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: apiKey,
        },
      });

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

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

      return results.map((place: any) => ({
        businessName: place.name,
        website: place.website || undefined,
        phone: place.tel || undefined,
        email: place.email || undefined,
        address: place.location?.formatted_address,
        city: params.location,
        category: place.categories?.[0]?.name || "Unknown",
        confidenceScore: 0.85,
        rawData: place,
      }));
    } catch (error) {
      console.error("Foursquare search failed:", error);
      throw error;
    }
  }

  async isAvailable(): Promise<boolean> {
    const apiKey = await getApiKey('foursquare');
    return !!apiKey;
  }
}
