import { NextResponse } from "next/server";
import { getSession } from "@/lib/auth";
import { renderTemplate } from "@/lib/waha";
import { validateTemplate } from "@/lib/reminders";

/**
 * Upgrade #9: Template Preview API
 *
 * POST /api/reminders/preview
 * Body: { message: "Hi {{name}}! Your {{treatment}} at {{clinic}}..." }
 *
 * Returns:
 * - rendered: the message with sample data filled in
 * - warnings: any unknown {{variables}} found
 * - charCount: character count of rendered message
 * - smsSegments: estimated WhatsApp message segments
 */
export async function POST(req: Request) {
  const session = await getSession();
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  let body: { message?: string };
  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
  }

  const message = body.message;
  if (!message || typeof message !== "string") {
    return NextResponse.json({ error: "Message is required" }, { status: 400 });
  }

  // Validate template
  const { clean, warnings } = validateTemplate(message);

  // Sample data for preview
  const sampleVars: Record<string, string> = {
    name: "Sarah",
    treatment: "Teeth Whitening",
    clinic: session.name,
    date: "Monday, March 15",
    time: "2:30 PM",
    prepInstructions: "• Avoid coffee and tea 24 hours before\n• Brush and floss before your visit\n• Arrive 10 minutes early",
    aftercareInstructions: "• Avoid colored foods for 48 hours\n• Use the provided whitening toothpaste\n• Contact us if you experience sensitivity",
    address: "Our clinic",
    confirmLink: `${process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000"}/api/confirm/sample-id?token=sample-token`,
  };

  const rendered = renderTemplate(clean, sampleVars);
  const charCount = rendered.length;

  // WhatsApp message segments (~4096 chars per message)
  const segments = Math.ceil(charCount / 4096);

  return NextResponse.json({
    rendered,
    warnings,
    charCount,
    segments,
    isValid: warnings.length === 0,
  });
}
