// src/lib/gsc/search-analytics.ts — GSC searchAnalytics REST (no googleapis dep).
import "server-only";
import {
  parseSearchAnalytics,
  parseSearchAnalyticsCountries,
  parseSearchAnalyticsPages,
} from "./parse";
import type { GscQueryCountryRow, GscQueryPageRow, GscQueryRow } from "./types";

function isoDaysAgo(days: number): string {
  const d = new Date();
  d.setUTCDate(d.getUTCDate() - days);
  return d.toISOString().slice(0, 10);
}

/** Query GSC searchAnalytics for a property, dimension=query.
 *  `countryIso3` (alpha-3 lowercase, e.g. "fra") filters rows to one country. */
export async function querySearchAnalytics(
  accessToken: string,
  property: string,
  opts: { days?: number; rowLimit?: number; countryIso3?: string } = {},
): Promise<GscQueryRow[]> {
  const days = opts.days ?? 28;
  const url = `https://www.googleapis.com/webmasters/v3/sites/${encodeURIComponent(
    property,
  )}/searchAnalytics/query`;
  const res = await fetch(url, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${accessToken}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      startDate: isoDaysAgo(days),
      endDate: isoDaysAgo(0),
      dimensions: ["query"],
      rowLimit: opts.rowLimit ?? 1000,
      ...(opts.countryIso3
        ? {
            dimensionFilterGroups: [
              {
                filters: [
                  {
                    dimension: "country",
                    operator: "equals",
                    expression: opts.countryIso3,
                  },
                ],
              },
            ],
          }
        : {}),
    }),
  });
  if (!res.ok) {
    throw new Error(`GSC searchAnalytics failed: HTTP ${res.status}`);
  }
  return parseSearchAnalytics(await res.json());
}

/** Query GSC searchAnalytics, dimensions=[query, page]. */
export async function querySearchAnalyticsPages(
  accessToken: string,
  property: string,
  opts: { days?: number; rowLimit?: number } = {},
): Promise<GscQueryPageRow[]> {
  const days = opts.days ?? 28;
  const url = `https://www.googleapis.com/webmasters/v3/sites/${encodeURIComponent(
    property,
  )}/searchAnalytics/query`;
  const res = await fetch(url, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${accessToken}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      startDate: isoDaysAgo(days),
      endDate: isoDaysAgo(0),
      dimensions: ["query", "page"],
      rowLimit: opts.rowLimit ?? 1000,
    }),
  });
  if (!res.ok) {
    throw new Error(`GSC searchAnalytics (pages) failed: HTTP ${res.status}`);
  }
  return parseSearchAnalyticsPages(await res.json());
}

/** Query GSC searchAnalytics, dimensions=[query, country] (all countries).
 *  Powers per-query language attribution: a query ranking only in markets that
 *  map to no configured language is dropped by the sync. Country is returned as
 *  alpha-2 (mapped from GSC's alpha-3). */
export async function querySearchAnalyticsByCountry(
  accessToken: string,
  property: string,
  opts: { days?: number; rowLimit?: number } = {},
): Promise<GscQueryCountryRow[]> {
  const days = opts.days ?? 28;
  const url = `https://www.googleapis.com/webmasters/v3/sites/${encodeURIComponent(
    property,
  )}/searchAnalytics/query`;
  const res = await fetch(url, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${accessToken}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      startDate: isoDaysAgo(days),
      endDate: isoDaysAgo(0),
      dimensions: ["query", "country"],
      rowLimit: opts.rowLimit ?? 1000,
    }),
  });
  if (!res.ok) {
    throw new Error(`GSC searchAnalytics (country) failed: HTTP ${res.status}`);
  }
  return parseSearchAnalyticsCountries(await res.json());
}
