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

/**
 * Logic for Umami Smart Proxy Route Handler.
 */
export function createUmamiProxyHandler(config: {
  websiteId?: string;
  apiEndpoint: string;
}) {
  return async function POST(request: NextRequest) {
    try {
      const body = await request.json();
      const { type, payload } = body;

      if (!config.websiteId) {
        return NextResponse.json({ status: "ignored" }, { status: 200 });
      }

      const enhancedPayload = {
        ...payload,
        website: config.websiteId,
      };

      const response = await fetch(`${config.apiEndpoint}/api/send`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "User-Agent": request.headers.get("user-agent") || "Mintel-Proxy",
          "X-Forwarded-For": request.headers.get("x-forwarded-for") || "",
        },
        body: JSON.stringify({ type, payload: enhancedPayload }),
      });

      if (!response.ok) {
        const errorText = await response.text();
        return new NextResponse(errorText, { status: response.status });
      }

      return NextResponse.json({ status: "ok" });
    } catch (_error) {
      return NextResponse.json(
        { error: "Internal Server Error" },
        { status: 500 },
      );
    }
  };
}

/**
 * Logic for Sentry/GlitchTip Relay Route Handler.
 */
export function createSentryRelayHandler(config: { dsn?: string }) {
  return async function POST(request: NextRequest) {
    try {
      const envelope = await request.text();
      const lines = envelope.split("\n");
      if (lines.length < 1) {
        return NextResponse.json({ error: "Empty envelope" }, { status: 400 });
      }

      if (!config.dsn) {
        return NextResponse.json({ status: "ignored" }, { status: 200 });
      }

      const dsnUrl = new URL(config.dsn);
      const projectId = dsnUrl.pathname.replace("/", "");
      const relayUrl = `${dsnUrl.protocol}//${dsnUrl.host}/api/${projectId}/envelope/`;

      const response = await fetch(relayUrl, {
        method: "POST",
        body: envelope,
        headers: {
          "Content-Type": "application/x-sentry-envelope",
        },
      });

      if (!response.ok) {
        const errorText = await response.text();
        return new NextResponse(errorText, { status: response.status });
      }

      return NextResponse.json({ status: "ok" });
    } catch (_error) {
      return NextResponse.json(
        { error: "Internal Server Error" },
        { status: 500 },
      );
    }
  };
}
