import { NextRequest, NextResponse } from "next/server";

export async function GET(req: NextRequest) {
  const domain = req.nextUrl.searchParams.get("domain")?.trim().toLowerCase();
  if (!domain) return NextResponse.json({ error: "domain required" }, { status: 400 });
  if (!/^[a-zA-Z0-9._\-]+$/.test(domain)) {
    return NextResponse.json({ error: "Invalid domain" }, { status: 400 });
  }

  try {
    // OpenID Connect discovery endpoint
    const oidcUrl = `https://login.microsoftonline.com/${domain}/.well-known/openid-configuration`;
    const oidcRes = await fetch(oidcUrl, { signal: AbortSignal.timeout(10000) });

    if (!oidcRes.ok) {
      return NextResponse.json({ error: `Microsoft returned ${oidcRes.status} — domain may not use Microsoft 365` }, { status: 200 });
    }

    const oidc = await oidcRes.json();
    const tenantId = oidc.token_endpoint?.match(/login\.microsoftonline\.com\/([^/]+)\//)?.[1] ?? null;

    // Federation metadata
    let federationInfo = null;
    try {
      const fedRes = await fetch(`https://login.microsoftonline.com/${domain}/FederationMetadata/2007-06/FederationMetadata.xml`, { signal: AbortSignal.timeout(5000) });
      federationInfo = fedRes.ok ? "federated" : "managed";
    } catch {
      federationInfo = "managed";
    }

    // Get tenant brand info
    let tenantDisplayName = null;
    let tenantRegion = null;
    try {
      const brandRes = await fetch(`https://login.microsoftonline.com/${tenantId ?? domain}/v2.0/.well-known/openid-configuration`, { signal: AbortSignal.timeout(5000) });
      if (brandRes.ok) {
        const brandData = await brandRes.json();
        tenantRegion = brandData.cloud_instance_name ?? null;
      }
    } catch { /* skip */ }

    // Get domain info from tenant
    const endpoints = {
      authorization: oidc.authorization_endpoint,
      token: oidc.token_endpoint,
      jwks: oidc.jwks_uri,
      userinfo: oidc.userinfo_endpoint,
    };

    return NextResponse.json({
      domain,
      tenantId,
      authType: federationInfo,
      tenantDisplayName,
      tenantRegion,
      cloudEnvironment: oidc.cloud_instance_name ?? "AzureCloud",
      issuer: oidc.issuer,
      endpoints,
      scopes: oidc.scopes_supported,
      responseTypes: oidc.response_types_supported,
    });
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : "lookup failed";
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
