import { NextRequest, NextResponse } from 'next/server';
import { eq } from 'drizzle-orm';
import { db } from '@/lib/db/client';
import { campaigns, campaignVariants, recipients, workspaces } from '@/lib/db/schema';
import { substituteTagsHtml } from '@/modules/sending/lib/tag-substitution';
import { buildFooterUrlTags } from '@/modules/sending/lib/footer-urls';

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

/**
 * Browser-View-Endpoint — rendert eine versendete Mail als Web-Page.
 *
 * URL-Form: `/api/track/view?c=CAMPAIGN_ID&r=RECIPIENT_ID[&v=VARIANT_ID]`
 *
 * Liefert das Variant-HTML (oder Fallback-Strategy._generated.emailHtml für alte
 * Single-Variant-Campaigns) mit System-Tags + customData-Spalten substituiert,
 * sodass der Empfänger die Mail genauso sieht wie in seinem Postfach.
 *
 * Tracking-Pixel/Click-Wrapper bleiben drin — wir wollen Page-Views NICHT als
 * "Open" zählen (false positives), deshalb wird das Pixel im Browser via
 * CSP/no-store ohnehin nochmal feuern aber per Default-De-Dupe (recipientId+
 * eventType+sameMinute) eh deduplitziert. Akzeptabler Trade-off.
 *
 * Keine Auth: das HTML enthält keine Geheimnisse, das HMAC-Token im Unsubscribe-
 * Link ist eigenständig geschützt, und der Empfänger kennt seine eigenen Daten.
 */
export async function GET(req: NextRequest) {
  const { searchParams } = req.nextUrl;
  const campaignId = searchParams.get('c');
  const recipientId = searchParams.get('r');
  const variantIdParam = searchParams.get('v');

  if (!campaignId || !recipientId) {
    return new NextResponse('Missing campaign or recipient parameter.', { status: 400 });
  }

  const campaign = db.select().from(campaigns).where(eq(campaigns.id, campaignId)).get();
  if (!campaign) return new NextResponse('Campaign not found.', { status: 404 });

  const recipient = db.select().from(recipients).where(eq(recipients.id, recipientId)).get();
  if (!recipient) return new NextResponse('Recipient not found.', { status: 404 });

  const workspace = db.select().from(workspaces).where(eq(workspaces.id, campaign.workspaceId)).get();
  if (!workspace) return new NextResponse('Workspace not found.', { status: 404 });

  // HTML-Source resolven: Variant oder Strategy._generated (Pre-Variant-Campaigns)
  let html: string | undefined;
  let variantId: string | null = null;
  if (variantIdParam) {
    const v = db.select().from(campaignVariants).where(eq(campaignVariants.id, variantIdParam)).get();
    if (v?.html) {
      html = v.html;
      variantId = v.id;
    }
  }
  if (!html) {
    const gen = (campaign.strategyJson as { _generated?: { emailHtml?: string } } | null)?._generated;
    if (gen?.emailHtml) html = gen.emailHtml;
  }
  if (!html) return new NextResponse('No rendered HTML available for this campaign.', { status: 404 });

  // Recipient-spezifische Tags substituieren — selbe Reihenfolge wie im Worker, sonst
  // sieht die Browser-View anders aus als die echte Mail.
  const firstName = recipient.firstName?.trim() || 'gemeinsam';
  const footerTags = buildFooterUrlTags({
    campaignId,
    variantId,
    recipientId,
    brandImprintUrl: workspace.imprintUrl,
    brandPrivacyUrl: workspace.privacyUrl,
  });
  const systemTags: Record<string, string> = {
    RECIPIENT_ID: recipient.id,
    CRM_ID: recipient.crmId ?? '',
    EMAIL: recipient.email,
    FIRST_NAME: firstName,
    ...footerTags,
  };
  html = substituteTagsHtml(html, systemTags);

  const customData = recipient.customDataJson as Record<string, unknown> | null;
  if (customData) {
    const reserved = new Set(Object.keys(systemTags));
    html = substituteTagsHtml(html, customData, { reservedKeys: reserved });
  }

  return new NextResponse(html, {
    status: 200,
    headers: {
      'Content-Type': 'text/html; charset=utf-8',
      'Cache-Control': 'no-store',
      'X-Robots-Tag': 'noindex, nofollow',
    },
  });
}
