const PSI_ENDPOINT = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed";
const PSI_TIMEOUT_MS = 30000;

export interface PsiResponse {
  lighthouseResult: {
    audits: Record<string, {
      id: string;
      title: string;
      description: string;
      score: number | null;
      displayValue?: string;
      details?: {
        type: string;
        items?: Array<Record<string, unknown>>;
        overallSavingsMs?: number;
        overallSavingsBytes?: number;
      };
      numericValue?: number;
      numericUnit?: string;
    }>;
    categories: {
      performance?: { score: number | null };
    };
  };
  loadingExperience?: {
    metrics?: {
      LARGEST_CONTENTFUL_PAINT_MS?: { percentile: number; category: string };
      INTERACTION_TO_NEXT_PAINT?: { percentile: number; category: string };
      CUMULATIVE_LAYOUT_SHIFT_SCORE?: { percentile: number; category: string };
      FIRST_CONTENTFUL_PAINT_MS?: { percentile: number; category: string };
      EXPERIMENTAL_TIME_TO_FIRST_BYTE?: { percentile: number; category: string };
    };
    overall_category?: string;
  };
}

export async function callPageSpeedInsights(
  url: string,
  strategy: "mobile" | "desktop",
): Promise<PsiResponse> {
  const params = new URLSearchParams({ url, strategy, category: "performance" });
  const endpoint = `${PSI_ENDPOINT}?${params.toString()}`;

  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), PSI_TIMEOUT_MS);

  try {
    const res = await fetch(endpoint, {
      method: "GET",
      signal: controller.signal,
      headers: { Accept: "application/json" },
    });
    clearTimeout(timer);

    if (!res.ok) {
      throw new Error(`PSI API returned ${res.status}: ${res.statusText}`);
    }

    return (await res.json()) as PsiResponse;
  } catch (err) {
    clearTimeout(timer);
    throw err;
  }
}
