/**
 * Google PageSpeed / Lighthouse Integration
 * --------------------------------------------
 * Auth: API key (no OAuth needed)
 * API: https://www.googleapis.com/pagespeedonline/v5/runPagespeed
 *
 * This is the simplest integration — just needs an API key.
 * Free tier: 25,000 requests/day.
 */

import type { IntegrationCredentials } from "@/lib/services/integration-credentials";
import { SyncService, SyncResult, apiCall } from "./types";

const API_BASE = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed";

export const googlePageSpeed: SyncService = {
  id: "pagespeed",
  name: "Google PageSpeed Insights",

  async connect(brandId: string, creds?: IntegrationCredentials): Promise<SyncResult> {
    // PageSpeed can work without credentials (uses env API key)
    const apiKey = creds?.apiKey || process.env.GOOGLE_PAGESPEED_API_KEY;
    if (!apiKey) {
      // PageSpeed API also works without a key (with lower rate limits)
      return {
        success: true,
        message: "PageSpeed connected (no API key — using free tier with lower rate limits).",
      };
    }

    return {
      success: true,
      message: "PageSpeed connected with API key.",
      credentials: { apiKey },
    };
  },

  async disconnect(): Promise<SyncResult> {
    return { success: true, message: "PageSpeed disconnected." };
  },

  async sync(brandId: string, creds?: IntegrationCredentials): Promise<SyncResult> {
    const apiKey = creds?.apiKey || process.env.GOOGLE_PAGESPEED_API_KEY || "";
    const siteUrl = creds?.siteUrl as string;

    if (!siteUrl) {
      return { success: false, message: "No site URL configured for PageSpeed audit." };
    }

    // Build the API URL
    const params = new URLSearchParams();
    params.set("url", siteUrl);
    params.set("strategy", "mobile");
    params.append("category", "performance");
    params.append("category", "accessibility");
    params.append("category", "best-practices");
    params.append("category", "seo");
    if (apiKey) params.set("key", apiKey);

    const res = await apiCall(`${API_BASE}?${params.toString()}`);

    if (!res.ok) {
      return { success: false, message: `PageSpeed audit failed: ${res.error}` };
    }

    const data = res.data as Record<string, unknown>;
    const lighthouse = data.lighthouseResult as Record<string, unknown> | undefined;
    const categories = lighthouse?.categories as Record<string, { score: number }> | undefined;

    return {
      success: true,
      message: "PageSpeed audit completed.",
      data: {
        performance: Math.round((categories?.performance?.score ?? 0) * 100),
        accessibility: Math.round((categories?.accessibility?.score ?? 0) * 100),
        bestPractices: Math.round((categories?.["best-practices"]?.score ?? 0) * 100),
        seo: Math.round((categories?.seo?.score ?? 0) * 100),
      },
    };
  },
};
