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

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

  const clinic = await prisma.clinic.findUnique({
    where: { id: session.id },
    select: { wahaStatus: true, wahaSessionId: true },
  });

  // If we have an active session, check Waha for real status
  if (clinic?.wahaSessionId) {
    try {
      const wahaStatus = await getSessionStatus();
      const status = wahaStatus?.status;

      let newStatus = clinic.wahaStatus;
      let qrCode = null;

      if (status === "WORKING") {
        newStatus = "connected";
      } else if (status === "SCAN_QR_CODE") {
        newStatus = "qr_pending";
        try {
          const qrData = await getQRCode();
          qrCode = qrData?.value || null;
        } catch { /* QR not ready */ }
      } else if (status === "STOPPED" || status === "FAILED") {
        newStatus = "disconnected";
      }

      // Sync to DB if changed
      if (newStatus !== clinic.wahaStatus) {
        await prisma.clinic.update({
          where: { id: session.id },
          data: { wahaStatus: newStatus },
        });
      }

      return NextResponse.json({
        status: newStatus,
        sessionId: clinic.wahaSessionId,
        qrCode,
        wahaReachable: true,
        wahaError: null,
      });
    } catch (err: any) {
      // Waha unreachable — report current DB status with warning
      const errMsg = err?.name === "AbortError" ? "WAHA timeout — is Docker running?" : err?.message ?? String(err);
      console.error("⚠️ WAHA unreachable:", errMsg);
      return NextResponse.json({
        status: "disconnected",
        sessionId: clinic.wahaSessionId,
        wahaReachable: false,
        wahaError: errMsg,
      });
    }
  }

  // No session stored — still check if WAHA server is reachable so the UI can warn
  const health = await checkWahaHealth();
  return NextResponse.json({
    status: clinic?.wahaStatus || "disconnected",
    sessionId: clinic?.wahaSessionId || null,
    wahaReachable: health.ok,
    wahaError: health.error ?? null,
  });
}
