import { NextRequest } from "next/server";

import { assertSameOrigin } from "@/lib/server/request-guards";
import { proxyHermesRequest, proxyHermesStreamRequest } from "@/lib/server/hermes-proxy";

type Params = {
  params: Promise<{
    path: string[];
  }>;
};

async function knowledgePath(request: NextRequest, context: Params) {
  const { path } = await context.params;
  return `/knowledge/${path.join("/")}${request.nextUrl.search}`;
}

function isDownloadPath(path: string) {
  return /\/documents\/\d+\/download(?:\?|$)/.test(path);
}

export async function GET(request: NextRequest, context: Params) {
  const path = await knowledgePath(request, context);
  if (isDownloadPath(path)) {
    return proxyHermesStreamRequest(request, path);
  }
  return proxyHermesRequest(request, path);
}

export async function POST(request: NextRequest, context: Params) {
  const originError = assertSameOrigin(request);
  if (originError) {
    return originError;
  }
  return proxyHermesRequest(request, await knowledgePath(request, context));
}

export async function PUT(request: NextRequest, context: Params) {
  const originError = assertSameOrigin(request);
  if (originError) {
    return originError;
  }
  return proxyHermesRequest(request, await knowledgePath(request, context));
}

export async function DELETE(request: NextRequest, context: Params) {
  const originError = assertSameOrigin(request);
  if (originError) {
    return originError;
  }
  return proxyHermesRequest(request, await knowledgePath(request, context));
}
