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

export async function POST() {
  const session = await getSession();
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  try {
    await stopSession();
  } catch {
    // Session might not exist — that's fine
  }

  await prisma.clinic.update({
    where: { id: session.id },
    data: { wahaStatus: "disconnected", wahaSessionId: null },
  });

  return NextResponse.json({ success: true });
}
