/**
 * POST /api/admin/trigger-ga4-sync
 *
 * Manual GA4 sync trigger for admin. Runs the same logic as the
 * daily integration-sync cron but returns detailed results per brand.
 * Accepts { brandId? } — when provided syncs only that brand.
 */

import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireSuperadmin } from "@/lib/admin-auth";
import { googleAnalytics } from "@/lib/integrations/google-analytics";
import { getCredentials } from "@/lib/services/integration-credentials";

export const dynamic = "force-dynamic";
export const maxDuration = 120;

export async function POST(req: Request) {
  const denied = await requireSuperadmin();
  if (denied) return denied;

  const body = await req.json().catch(() => ({})) as { brandId?: string };

  const where: Record<string, unknown> = { integrationId: "ga4", connected: true };
  if (body.brandId) where.brandId = body.brandId;

  const integrations = await prisma.brandIntegration.findMany({
    where,
    select: { brandId: true, brand: { select: { name: true, domain: true } } },
  });

  const results: Array<{
    brandId: string;
    name: string;
    domain: string;
    success: boolean;
    message: string;
    snapshotsCreated?: number;
  }> = [];

  for (const integ of integrations) {
    try {
      const creds = await getCredentials(integ.brandId, "ga4");
      if (!creds?.propertyId) {
        results.push({
          brandId: integ.brandId,
          name: integ.brand.name,
          domain: integ.brand.domain,
          success: false,
          message: "No GA4 propertyId configured",
        });
        continue;
      }

      const result = await googleAnalytics.sync(integ.brandId, creds);
      results.push({
        brandId: integ.brandId,
        name: integ.brand.name,
        domain: integ.brand.domain,
        success: result.success,
        message: result.message,
        snapshotsCreated: undefined,
      });
    } catch (err) {
      results.push({
        brandId: integ.brandId,
        name: integ.brand.name,
        domain: integ.brand.domain,
        success: false,
        message: err instanceof Error ? err.message : String(err),
      });
    }
  }

  return NextResponse.json({
    synced: results.length,
    success: results.filter((r) => r.success).length,
    failed: results.filter((r) => !r.success).length,
    results,
  });
}
