import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireRole } from "@/lib/auth";
import {
  fetchAnalyticsOverview,
  isAnalyticsConfigured,
} from "@/lib/google-analytics";

/** Central → Accounts → Google Analytics control panel:
    settings view/save + live statistics from the GA4 Data API. */

function analyticsView(row: {
  measurementId: string | null;
  propertyId: string | null;
  clientEmail: string | null;
  privateKey: string | null;
  active: boolean;
} | null) {
  if (!row) return null;
  const { privateKey, ...rest } = row;
  return { ...rest, hasKey: Boolean(privateKey) };
}

async function currentRow() {
  return prisma.analyticsSetting.findFirst({ where: { scope: "CENTRAL" }, orderBy: { id: "asc" } });
}

export async function GET(req: Request) {
  const session = await requireRole("SUPER_ADMIN");
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const row = await currentRow();
  const view = analyticsView(row);
  const withStats = new URL(req.url).searchParams.get("stats") === "1";

  if (!withStats) return NextResponse.json({ analytics: view });

  if (!view?.active) return NextResponse.json({ analytics: view, stats: null, statsError: "NOT_ACTIVE" });
  if (!row || !isAnalyticsConfigured(row)) {
    return NextResponse.json({ analytics: view, stats: null, statsError: "NOT_CONFIGURED" });
  }

  try {
    const stats = await fetchAnalyticsOverview({
      propertyId: row.propertyId,
      clientEmail: row.clientEmail,
      privateKey: row.privateKey,
    });
    return NextResponse.json({ analytics: view, stats });
  } catch (err) {
    const message = err instanceof Error ? err.message : "GA_FAILED";
    return NextResponse.json({ analytics: view, stats: null, statsError: message });
  }
}

export async function PUT(req: Request) {
  const session = await requireRole("SUPER_ADMIN");
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  try {
    const body = (await req.json().catch(() => ({}))) as {
      measurementId?: string;
      propertyId?: string;
      clientEmail?: string;
      privateKey?: string;
      active?: boolean;
    };
    const str = (v: unknown) => (typeof v === "string" ? v.trim() : "");
    const measurementId = str(body.measurementId) || null;
    const propertyId = str(body.propertyId).replace(/\D/g, "") || null;
    const clientEmail = str(body.clientEmail) || null;

    const existing = await currentRow();
    const privateKey = str(body.privateKey) || existing?.privateKey || null;

    if (measurementId && !/^G-[A-Z0-9]+$/i.test(measurementId)) {
      return NextResponse.json({ error: "INVALID_MEASUREMENT_ID" }, { status: 400 });
    }
    if (propertyId && !/^\d+$/.test(propertyId)) {
      return NextResponse.json({ error: "INVALID_PROPERTY_ID" }, { status: 400 });
    }
    if (clientEmail && !clientEmail.includes("@")) {
      return NextResponse.json({ error: "INVALID_CLIENT_EMAIL" }, { status: 400 });
    }

    const data = { measurementId, propertyId, clientEmail, privateKey, active: body.active !== false };
    if (existing) await prisma.analyticsSetting.update({ where: { id: existing.id }, data });
    else await prisma.analyticsSetting.create({ data: { ...data, scope: "CENTRAL", institutionId: null } });

    return NextResponse.json({ ok: true });
  } catch {
    return NextResponse.json({ error: "Could not save analytics settings" }, { status: 500 });
  }
}
