import { NextResponse } from "next/server";
import { logApiError } from "@/lib/api/security";
import { buildAuthPolicyPreview } from "@/lib/organization-auth";

export async function GET(req: Request) {
  try {
    const url = new URL(req.url);
    const email = String(url.searchParams.get("email") || "").trim().toLowerCase();

    if (!email || !email.includes("@")) {
      return NextResponse.json({
        email,
        domain: null,
        matchedOrganizations: [],
        allowedMethods: ["password", "magic_link", "google", "github", "azure"],
        autoJoinEnabled: false,
      });
    }

    const preview = await buildAuthPolicyPreview(email);
    return NextResponse.json(preview);
  } catch (error) {
    logApiError("Auth policy lookup error", error);
    return NextResponse.json(
      { error: "Failed to load auth policy preview" },
      { status: 500 }
    );
  }
}
