/**
 * WhatsApp Business Disconnection API
 *
 * POST /api/integrations/whatsapp/disconnect
 *
 * Disconnects user's WhatsApp Business account by:
 * 1. Deactivating stored access token
 * 2. Clearing connection status
 * 3. Logging the disconnection
 *
 * Security:
 * - Requires authenticated user session
 * - Validates user ownership
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { whatsappService } from "@/lib/services/whatsapp.service";
import { logger } from "@/lib/logger";

interface DisconnectResponse {
  success: boolean;
  message?: string;
  error?: string;
}

export async function POST(request: NextRequest) {
  try {
    // Authenticate user
    const session = await auth();
    if (!session?.user?.id) {
      return NextResponse.json<DisconnectResponse>(
        { success: false, error: "Unauthorized. Please log in." },
        { status: 401 },
      );
    }

    const userId = session.user.id;

    logger.info("WhatsApp disconnection attempt", { userId });

    // Disconnect WhatsApp
    const result = await whatsappService.disconnectWhatsApp(userId);

    if (!result.success) {
      return NextResponse.json<DisconnectResponse>(
        {
          success: false,
          error: result.error || "Failed to disconnect WhatsApp",
        },
        { status: 400 },
      );
    }

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

        await convexMutation("whatsapp/mutations:updateWhatsappConfig", {
          email: session.user.email || "",
          whatsappConnected: false,
          whatsappNumber: "",
        });
      } catch (convexError) {
        console.error("[Convex replicate] whatsapp disconnect:", convexError);
        // Non-blocking: Prisma already succeeded
      }
    }

    // Log disconnection

    logger.info("WhatsApp disconnected successfully", { userId });

    return NextResponse.json<DisconnectResponse>(
      {
        success: true,
        message: "WhatsApp Business account disconnected successfully",
      },
      { status: 200 },
    );
  } catch (error) {
    logger.error("WhatsApp disconnection endpoint error", error);
    return NextResponse.json<DisconnectResponse>(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}

// Only allow POST method
export async function GET() {
  return NextResponse.json({ error: "Method not allowed" }, { status: 405 });
}
