import { NextRequest, NextResponse } from "next/server";
import { validateStaffSession } from "@/lib/staff-session";
import {
  getIntegrationsSummary,
  getIntegrationUsers,
  getIntegrationErrors,
  getIntegrationHealthStats,
  type IntegrationType,
  type IntegrationStatus,
  type IntegrationHealthFilters,
} from "@/lib/services/integration-monitor.service";
// Convex routing (WU-13): integration-monitor.service encapsulates its own Prisma queries. Needs service migration.

export async function GET(request: NextRequest) {
  try {
    const session = await validateStaffSession(request);
    if (
      !session ||
      (session.role !== "ADMIN" && session.role !== "SUPER_ADMIN")
    ) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { searchParams } = new URL(request.url);
    const action = searchParams.get("action");

    // Get overall health stats
    if (action === "stats") {
      const stats = await getIntegrationHealthStats();
      return NextResponse.json(stats);
    }

    // Get summary of all integration types
    if (action === "summary") {
      const summary = await getIntegrationsSummary();
      return NextResponse.json({ summary });
    }

    // Get integrations with errors
    if (action === "errors") {
      const type = searchParams.get("type") as IntegrationType | null;
      const { errors } = await getIntegrationErrors(type || undefined);
      return NextResponse.json({ errors });
    }

    // Get users with integrations (default action)
    const filters: IntegrationHealthFilters = {};

    const type = searchParams.get("type");
    if (type) filters.type = type as IntegrationType;

    const status = searchParams.get("status");
    if (status) filters.status = status as IntegrationStatus;

    const search = searchParams.get("search");
    if (search) filters.search = search;

    const page = searchParams.get("page");
    if (page) filters.page = parseInt(page, 10);

    const limit = searchParams.get("limit");
    if (limit) filters.limit = parseInt(limit, 10);

    const result = await getIntegrationUsers(filters);
    return NextResponse.json(result);
  } catch (error) {
    console.error("Failed to fetch integrations:", error);
    return NextResponse.json(
      { error: "Failed to fetch integrations" },
      { status: 500 },
    );
  }
}
