// src/lib/content/online.ts — published-content performance rows + KPI stats.
import { normalizeUrl } from "@/lib/content/stats-logic";

export interface OnlineRow {
  id: string;
  title: string;
  url: string | null;
  keywordTerm: string | null;
  keywordCountry: string | null;
  position: number | null;
  clicks: number;
  impressions: number;
  ctr: number | null;
  gscPage: string | null;
}

/** true quand la page qui ranke (GSC) diffère de l'URL de l'article. */
export function gscPageMismatch(
  articleUrl: string | null,
  gscPage: string | null | undefined,
): boolean {
  if (!articleUrl || !gscPage) return false;
  return normalizeUrl(articleUrl) !== normalizeUrl(gscPage);
}

export interface OnlineStats {
  published: number;
  totalClicks: number;
  totalImpressions: number;
  avgPosition: number | null;
}

export function buildOnlineStats(rows: OnlineRow[]): OnlineStats {
  const withPos = rows.filter((r) => r.position != null);
  return {
    published: rows.length,
    totalClicks: rows.reduce((s, r) => s + r.clicks, 0),
    totalImpressions: rows.reduce((s, r) => s + r.impressions, 0),
    avgPosition: withPos.length
      ? Math.round(
          (withPos.reduce((s, r) => s + (r.position as number), 0) /
            withPos.length) *
            10,
        ) / 10
      : null,
  };
}
