import { NextResponse } from "next/server";
import { getSession } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { createSession, getQRCode, SESSION_NAME } from "@/lib/waha";

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

  try {
    // Create/start Waha session (always "default" for CORE)
    await createSession();

    // Update clinic with session info
    await prisma.clinic.update({
      where: { id: session.id },
      data: { wahaSessionId: SESSION_NAME, wahaStatus: "qr_pending" },
    });

    // Try to get QR code (may not be ready yet)
    let qrCode = null;
    try {
      // Wait a moment for QR to generate
      await new Promise(r => setTimeout(r, 2000));
      const qrData = await getQRCode();
      qrCode = qrData?.value || null;
    } catch {
      // QR not ready — client will poll via status endpoint
    }

    return NextResponse.json({ success: true, sessionName: SESSION_NAME, qrCode });
  } catch (error) {
    console.error("Waha connect error:", error);
    return NextResponse.json(
      { error: "Failed to connect. Make sure Waha is running on " + (process.env.WAHA_API_URL || "http://localhost:3005") },
      { status: 500 }
    );
  }
}
