import { NextResponse } from "next/server";

import { auth } from "@/lib/auth";
import { getActiveOrgIdFromSession } from "@/lib/auth-guards";
import { getClientIp, rateLimit } from "@/lib/rate-limit";
import { resolveReachableUrl } from "@/lib/url";

const API_URL = process.env.SITESPEED_API_URL || "https://speed.elevaseo.app";
const API_KEY = process.env.SITESPEED_API_KEY || "";

export async function POST(req: Request) {
  // Auth gate — this route is NOT public. It forwards an arbitrary URL to
  // the sitespeed worker (which drives a real browser against it) and to
  // an unfiltered server-side `fetch` (see lib/url.ts#isReachable). Without
  // a session check, anonymous callers could probe internal infra (SSRF)
  // or burn worker quota at zero cost.
  const session = await auth.api.getSession({ headers: req.headers });
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const orgId = await getActiveOrgIdFromSession(session);
  if (!orgId) return NextResponse.json({ error: "No active organization" }, { status: 403 });

  // Per-user rate limit — protects the sitespeed worker from a signed-in
  // user firing tests in a loop, independently of the per-org test quota.
  const ip = getClientIp(new Headers(req.headers));
  const rl = rateLimit(`speed-test:${session.user.id}:${ip}`, { max: 10, windowMs: 60_000 });
  if (!rl.ok) {
    return NextResponse.json(
      { error: "Too many requests" },
      { status: 429, headers: { "Retry-After": String(rl.retryAfter) } },
    );
  }

  const body = await req.json();
  const { url, ...rest } = body ?? {};

  if (!url || typeof url !== "string") {
    return NextResponse.json({ error: "URL requise" }, { status: 400 });
  }

  let fullUrl: string;
  try {
    fullUrl = (await resolveReachableUrl(url)).url;
  } catch (err) {
    return NextResponse.json(
      { error: err instanceof Error ? err.message : "URL invalide" },
      { status: 400 },
    );
  }

  const res = await fetch(`${API_URL}/api/test`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ ...rest, url: fullUrl }),
  });

  const data = await res.json();
  return NextResponse.json(data, { status: res.status });
}
