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

import { getSocialAuthDiagnostics } from "../../../../lib/social-auth-config";
import { getTrustedOriginDiagnostics } from "../_shared/cors";
import { buildProxyTrustedOriginDebugSnapshot } from "../_shared/trusted-origin-debug";
import { inspectOriginMapForRequest, inspectUpstreamConfig } from "../_shared/upstream";

export const dynamic = "force-dynamic";

function hasValue(value: string | undefined): boolean {
  return typeof value === "string" && value.trim().length > 0;
}

function parseTrustedOrigins(raw: string | undefined): string[] {
  return (raw ?? "")
    .split(",")
    .map((value) => value.trim())
    .filter(Boolean);
}

function normalizeAuthBasePath(raw: string | undefined): string {
  const configured = raw?.trim();
  if (!configured || configured === "/") return "/api/auth";
  return configured.startsWith("/") ? configured : `/${configured}`;
}

export async function GET(request: NextRequest) {
  const trustedOriginsRaw = process.env.TRUSTED_ORIGINS;
  const trustedOrigins = parseTrustedOrigins(trustedOriginsRaw);
  const trustedOriginDiagnostics = getTrustedOriginDiagnostics(
    request.headers.get("origin"),
    trustedOriginsRaw,
  );
  const originMapInspection = inspectOriginMapForRequest(request);
  const upstreamInspection = inspectUpstreamConfig(request);

  const smtpHostSet = hasValue(process.env.SMTP_HOST);
  const smtpUserSet = hasValue(process.env.SMTP_USER);
  const smtpPassSet = hasValue(process.env.SMTP_PASS);
  const smtpFromAddressSet = hasValue(process.env.SMTP_FROM_ADDRESS);
  const smtpConfigured = smtpHostSet && smtpUserSet && smtpPassSet && smtpFromAddressSet;
  const smtpConfigurationError =
    smtpHostSet && !smtpConfigured
      ? "SMTP_HOST is set, but SMTP_USER/SMTP_PASS/SMTP_FROM_ADDRESS are incomplete."
      : null;

  const payload = {
    defaultApiOrigin: process.env.NEXT_PUBLIC_AUTH_BASE_URL?.trim() ?? null,
    authBasePath: normalizeAuthBasePath(process.env.NEXT_PUBLIC_AUTH_BASE_PATH),
    upstreamAuthOrigin: process.env.ATHENA_AUTH_ORIGIN?.trim() ?? null,
    proxyOriginMap: originMapInspection,
    proxyUpstream: upstreamInspection.ok
      ? {
          ok: true,
          source: upstreamInspection.source,
          raw: upstreamInspection.upstreamRaw,
          resolved: upstreamInspection.upstreamBase.toString(),
        }
      : {
          ok: false,
          code: upstreamInspection.code,
          message: upstreamInspection.message,
          details: upstreamInspection.details,
        },
    trustedOrigins,
    trustedOriginsRaw: trustedOriginsRaw ?? "",
    trustedOriginDiagnostics,
    proxyOriginDebug: buildProxyTrustedOriginDebugSnapshot(request.headers.get("origin")),
    smtpConfigured,
    smtpConfigurationError,
    smtpFromAddressConfigured: smtpFromAddressSet,
    emailDeliveryEvidence:
      smtpConfigured
        ? "SMTP environment looks complete in this Next.js runtime."
        : "Password reset acceptance does not prove delivery unless SMTP is configured.",
    social: getSocialAuthDiagnostics(),
  };

  return NextResponse.json(payload, { status: 200 });
}

