/**
 * WhatsApp Integration Setup API
 * POST: Connect WhatsApp via n8n workflow
 * DELETE: Disconnect WhatsApp
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import prisma from "@/lib/db";
import { withCSRF } from "@/lib/csrf";
import { getDataSource } from "@/lib/data-source";

export const POST = withCSRF(async (req: NextRequest) => {
  try {
    const session = await auth();
    if (!session?.user?.id) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const body = await req.json();
    const { n8nWebhookUrl, n8nWorkflowId, whatsappNumber } = body;

    if (!n8nWebhookUrl || !whatsappNumber) {
      return NextResponse.json(
        { error: "n8nWebhookUrl and whatsappNumber are required" },
        { status: 400 },
      );
    }

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

        const connectedAt = Date.now();
        await convexMutation("whatsapp/mutations:updateWhatsappConfig", {
          email: session.user.email || "",
          whatsappConnected: true,
          whatsappNumber,
          whatsappConnectedAt: connectedAt,
          n8nWebhookUrl,
          n8nWorkflowId: n8nWorkflowId || undefined,
        });

        // Create notification via Convex if notifications domain also on Convex
        if (getDataSource("notifications") === "convex") {
          try {
            await convexMutation("notifications/mutations:create", {
              userId: session.user.email || "",
              type: "system_alert",
              title: "WhatsApp Connected",
              message: `WhatsApp Business number ${whatsappNumber} connected successfully`,
              metadata: { n8nWorkflowId, whatsappNumber },
            });
          } catch {
            // Non-blocking: notification creation failure should not block connect
          }
        }

        return NextResponse.json({
          success: true,
          whatsapp: {
            connected: true,
            phoneNumber: whatsappNumber,
            connectedAt: new Date(connectedAt).toISOString(),
            n8nWebhookUrl,
            n8nWorkflowId,
          },
        });
      } catch (error) {
        console.error("[Convex fallback] whatsapp connect:", error);
        // Fall through to Prisma
      }
    }

    // ── Prisma path (primary or fallback) ──────────────────────────────
    // Update user with WhatsApp connection details
    const user = await prisma.users.update({
      where: { id: session.user.id },
      data: {
        n8nWebhookUrl,
        n8nWorkflowId,
        whatsappNumber,
        whatsappConnected: true,
        whatsappConnectedAt: new Date(),
      },
    });

    // Create notification
    await prisma.notification.create({
      data: {
        userId: session.user.id,
        type: "system_alert",
        title: "WhatsApp Connected",
        message: `WhatsApp Business number ${whatsappNumber} connected successfully`,
        metadata: { n8nWorkflowId, whatsappNumber },
      },
    });

    return NextResponse.json({
      success: true,
      whatsapp: {
        connected: true,
        phoneNumber: whatsappNumber,
        connectedAt: user.whatsappConnectedAt,
        n8nWebhookUrl: user.n8nWebhookUrl,
        n8nWorkflowId: user.n8nWorkflowId,
      },
    });
  } catch (error) {
    console.error("Failed to connect WhatsApp:", error);
    return NextResponse.json(
      { error: "Failed to connect WhatsApp" },
      { status: 500 },
    );
  }
});

export const DELETE = withCSRF(async (req: NextRequest) => {
  try {
    const session = await auth();
    if (!session?.user?.id) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

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

        await convexMutation("whatsapp/mutations:updateWhatsappConfig", {
          email: session.user.email || "",
          whatsappConnected: false,
          n8nWebhookUrl: "",
          n8nWorkflowId: "",
          // Keep whatsappNumber for history
        });

        return NextResponse.json({ success: true });
      } catch (error) {
        console.error("[Convex fallback] whatsapp disconnect:", error);
        // Fall through to Prisma
      }
    }

    // ── Prisma path (primary or fallback) ──────────────────────────────
    // Disconnect WhatsApp
    await prisma.users.update({
      where: { id: session.user.id },
      data: {
        whatsappConnected: false,
        n8nWebhookUrl: null,
        n8nWorkflowId: null,
        // Keep whatsappNumber for history
      },
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("Failed to disconnect WhatsApp:", error);
    return NextResponse.json(
      { error: "Failed to disconnect WhatsApp" },
      { status: 500 },
    );
  }
});
