/**
 * Google Analytics 4 — Sync & Storage Service
 * -----------------------------------------------
 * Stores GA4 data and provides query functions for Dashboard
 * and Conversion Intelligence.
 */

import { prisma } from "@/lib/prisma";
import { log } from "@/lib/logger";

export interface Ga4Summary {
  sessions: number;
  users: number;
  pageViews: number;
  conversions: number;
  bounceRate: number;
  period: { startDate: string; endDate: string };
}

/**
 * Store GA4 sync data into MetricSnapshot for the Dashboard.
 */
export async function storeGa4Data(
  brandId: string,
  rows: Array<{ date: string; sessions: number; users: number; pageViews: number; conversions: number; bounceRate: number }>,
  startDate: string,
  endDate: string
): Promise<number> {
  let stored = 0;

  for (const row of rows) {
    const date = new Date(row.date);

    // Safeguard: GA4 "key events" counts conversion EVENTS, not
    // converting sessions. A ratio > 3x is suspicious — most real
    // conversion setups produce < 1 key event per session. Skip
    // writing the conversions value when clearly inflated so we
    // don't pollute charts with eventCount-level numbers.
    let safeConversions = row.conversions;
    if (row.sessions > 10 && row.conversions > row.sessions * 3) {
      console.warn(`[ga4-sync] Skipping inflated conversions: ${row.conversions} key events vs ${row.sessions} sessions for brand ${brandId} on ${row.date}.`);
      safeConversions = 0;
    }

    await prisma.metricSnapshot.upsert({
      where: { brandId_date_source: { brandId, date, source: "ga4" } },
      create: {
        brandId,
        date,
        source: "ga4",
        sessions: row.sessions,
        users: row.users,
        pageviews: row.pageViews,
        conversions: safeConversions,
        bounceRate: row.bounceRate,
      },
      update: {
        sessions: row.sessions,
        users: row.users,
        pageviews: row.pageViews,
        conversions: safeConversions,
        bounceRate: row.bounceRate,
      },
    });
    stored++;
  }

  log.info("integration", `Stored ${stored} days of GA4 data`, {
    metadata: { brandId, startDate, endDate },
  });

  return stored;
}

/**
 * Get GA4 summary for a brand — used by Dashboard and AI Avatar.
 */
export async function getGa4Summary(brandId: string, days: number = 28): Promise<Ga4Summary | null> {
  const since = new Date(Date.now() - days * 86400000);

  const snapshots = await prisma.metricSnapshot.findMany({
    where: { brandId, date: { gte: since }, source: "ga4" },
    orderBy: { date: "desc" },
  });

  if (snapshots.length === 0) return null;

  return {
    sessions: snapshots.reduce((s, r) => s + r.sessions, 0),
    users: snapshots.reduce((s, r) => s + r.users, 0),
    pageViews: snapshots.reduce((s, r) => s + r.pageviews, 0),
    conversions: snapshots.reduce((s, r) => s + r.conversions, 0),
    bounceRate: snapshots.length > 0
      ? Math.round((snapshots.reduce((s, r) => s + r.bounceRate, 0) / snapshots.length) * 10) / 10
      : 0,
    period: {
      startDate: since.toISOString().split("T")[0],
      endDate: new Date().toISOString().split("T")[0],
    },
  };
}
