import { NextResponse } from "next/server";
import { getSession } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { stopSession, deleteSession } from "@/lib/waha";

/**
 * DELETE /api/whatsapp/delete
 * Fully removes the WhatsApp session from WAHA (stops + deletes).
 * This clears all session data including stored auth/credentials.
 * Use this when the user wants to completely remove the connection.
 */
export async function POST() {
  const session = await getSession();
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  try {
    // Stop session first
    try {
      await stopSession();
    } catch {
      // Session might not be running — that's fine
    }

    // Delete session entirely from WAHA (removes stored auth data)
    try {
      await deleteSession();
    } catch {
      // Session might not exist — that's fine
    }
  } catch {
    // Even if WAHA is unreachable, clear local state
  }

  // Clear clinic's WhatsApp state
  await prisma.clinic.update({
    where: { id: session.id },
    data: {
      wahaStatus: "disconnected",
      wahaSessionId: null,
      wahaLastChecked: null,
    },
  });

  return NextResponse.json({ success: true, message: "WhatsApp connection fully deleted" });
}
