import { NextRequest, NextResponse } from "next/server";
import { logger } from "@/lib/logger";
import { prisma } from "@/lib/db";
import { contactSubmissionsAdapter } from "@/lib/adapters/contacts";
import { v4 as uuidv4 } from "uuid";
import { getDataSource } from "@/lib/data-source";
import { whatsappTrackSchema } from "@/lib/validators/api-schemas";

/**
 * POST - Receive webhook from n8n when demo conversation events occur.
 * Tracks WhatsApp demo sessions for analytics and lead capture.
 */
export async function POST(req: NextRequest) {
  try {
    // Validate webhook secret
    const webhookSecret = req.headers.get("x-webhook-secret");
    if (webhookSecret !== process.env.DEMO_WEBHOOK_SECRET) {
      logger.warn("Unauthorized demo webhook attempt", {
        ip: req.headers.get("x-forwarded-for") || "unknown",
      });
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const body = await req.json();
    const parsed = whatsappTrackSchema.safeParse(body);

    if (!parsed.success) {
      return NextResponse.json(
        { error: parsed.error.errors.map(e => e.message).join(", ") },
        { status: 400 },
      );
    }

    const { event, phone, industry, metadata } = parsed.data;

    logger.info("Demo webhook received", {
      event,
      hasPhone: !!phone,
      industry: industry || "not_specified",
    });

    // Track demo event as a contact submission for visibility in staff dashboard
    if (phone && event === "demo_completed") {
      let savedViaConvex = false;

      // ── Convex data-source branch (contact_submissions → support domain) ──
      if (getDataSource("support") === "convex") {
        try {
          const { convexMutation } = await import("@/lib/convex-client");

          await convexMutation("support/mutations:createContactSubmission", {
            name: "WhatsApp Demo User",
            email: `demo-${phone.replace(/\D/g, "").slice(-8)}@demo.mawidi.com`,
            phone,
            topic: "whatsapp_demo",
            message: JSON.stringify({
              event,
              industry: industry || "not_specified",
              ...(metadata || {}),
            }),
            preferred_language: "en",
            consent: false,
            ip_address:
              req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
              undefined,
            user_agent: req.headers.get("user-agent") || undefined,
          });

          savedViaConvex = true;
          logger.info("Demo lead tracked via Convex", {
            phone: phone.slice(-4).padStart(phone.length, "*"),
            event,
          });
        } catch (convexError) {
          logger.warn(
            "Convex contact submission failed, falling through to Prisma",
            {
              error:
                convexError instanceof Error
                  ? convexError.message
                  : String(convexError),
            },
          );
          // Fall through to Prisma path below
        }
      }

      // ── Prisma path (fallback or primary) ──────────────────────────────
      if (!savedViaConvex) {
        try {
          const now = new Date();
          await contactSubmissionsAdapter.create({
            data: {
              id: uuidv4(),
              name: "WhatsApp Demo User",
              email: `demo-${phone.replace(/\D/g, "").slice(-8)}@demo.mawidi.com`,
              phone,
              topic: "whatsapp_demo",
              message: JSON.stringify({
                event,
                industry: industry || "not_specified",
                ...(metadata || {}),
              }),
              preferred_language: "en",
              consent: false,
              status: "demo_lead",
              ip_address:
                req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
                null,
              user_agent: req.headers.get("user-agent") || null,
              created_at: now,
              updated_at: now,
            },
          });

          logger.info("Demo lead tracked", {
            phone: phone.slice(-4).padStart(phone.length, "*"),
            event,
          });
        } catch (dbError) {
          // Non-blocking: log but don't fail the webhook
          logger.error("Failed to track demo lead", {
            error: dbError instanceof Error ? dbError.message : String(dbError),
            event,
          });
        }
      }
    }

    return NextResponse.json({ received: true, event });
  } catch (error) {
    logger.error("Demo webhook handler error", {
      error: error instanceof Error ? error.message : String(error),
      stack: error instanceof Error ? error.stack : undefined,
    });
    return NextResponse.json(
      { error: "Webhook handler failed" },
      { status: 500 },
    );
  }
}

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