import { NextRequest, NextResponse } from 'next/server';
import { eq } from 'drizzle-orm';
import { db } from '@/lib/db/client';
import { recipients, campaigns, workspaces, campaignVariants } from '@/lib/db/schema';
import {
  getSessionForRecipient,
  buildUtmContentMatch,
  validateServiceAccount,
  type Ga4ServiceAccount,
} from '@/modules/stats/lib/ga4-client';
import { withAuth } from '@/core/auth';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

/**
 * On-Demand GA4-Session-Lookup für einen Recipient.
 *
 * Flow:
 *  1. Recipient + Campaign + Workspace laden (Variant-Label für utm_content-Match)
 *  2. Workspace muss ga4PropertyId UND ga4CredentialsJson haben — sonst 412 (Precondition Failed)
 *  3. utm_content-Match-String bauen: "<variantLabel>-<recipientId>"
 *  4. GA4 Data API runReport mit dimensionFilter
 *  5. Top-Pages + Aggregat-Metriken zurückgeben
 *
 * Response: { ok, summary: { sessions, pageviews, ... } | null, configured: boolean }
 *  - `configured: false` → Workspace hat keine GA4-Config → UI zeigt "GA4 nicht konfiguriert"
 *  - `summary: null` + `configured: true` → Empfänger war nicht in GA4 sichtbar
 *  - `summary: {...}` → echte Session-Daten
 */

export const GET = withAuth<{ params: Promise<{ id: string }> }>(async (req: NextRequest, _ctx, { params }: { params: Promise<{ id: string }> }) => {
  const { id: recipientId } = await params;
  if (!recipientId) return NextResponse.json({ error: 'Missing recipient id' }, { status: 400 });

  const row = db
    .select({
      variantId: recipients.variantId,
      ga4PropertyId: workspaces.ga4PropertyId,
      ga4CredentialsJson: workspaces.ga4CredentialsJson,
      attributionLookbackDays: workspaces.attributionLookbackDays,
    })
    .from(recipients)
    .innerJoin(campaigns, eq(campaigns.id, recipients.campaignId))
    .innerJoin(workspaces, eq(workspaces.id, campaigns.workspaceId))
    .where(eq(recipients.id, recipientId))
    .get();

  if (!row) return NextResponse.json({ error: 'Recipient not found' }, { status: 404 });

  // Pre-Condition: Workspace muss GA4-Config haben. Wenn nicht, "ok:true, configured:false"
  // damit das UI eine freundliche Message zeigen kann statt eines Errors.
  if (!row.ga4PropertyId || !row.ga4CredentialsJson) {
    return NextResponse.json({ ok: true, configured: false, summary: null });
  }

  let creds: Ga4ServiceAccount;
  try {
    creds = validateServiceAccount(row.ga4CredentialsJson);
  } catch (e) {
    return NextResponse.json(
      { ok: false, configured: true, error: `Invalid GA4 credentials: ${e instanceof Error ? e.message : 'unknown'}` },
      { status: 500 },
    );
  }

  // Variant-Label nachladen für utm_content-Match
  const variantLabel = row.variantId
    ? db
        .select({ label: campaignVariants.label })
        .from(campaignVariants)
        .where(eq(campaignVariants.id, row.variantId))
        .get()?.label ?? null
    : null;

  const utmMatch = buildUtmContentMatch(variantLabel, recipientId);
  const lookbackDays = row.attributionLookbackDays ?? 30;

  try {
    const summary = await getSessionForRecipient(creds, row.ga4PropertyId, utmMatch, lookbackDays);
    return NextResponse.json({
      ok: true,
      configured: true,
      utmContentMatch: utmMatch,
      lookbackDays,
      summary,
    });
  } catch (e) {
    return NextResponse.json(
      { ok: false, configured: true, error: e instanceof Error ? e.message : 'GA4 lookup failed' },
      { status: 502 },
    );
  }
});
