import { NextRequest } from "next/server";

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

type Params = {
  params: Promise<{
    id: string;
  }>;
};

async function proxyUserRequest(request: NextRequest, { params }: Params) {
  const { id } = await params;
  const action = request.nextUrl.searchParams.get("action");
  const path = action === "password" ? `/users/${id}/password` : `/users/${id}`;

  return proxyHermesRequest(request, path);
}

export async function GET(request: NextRequest, context: Params) {
  return proxyUserRequest(request, context);
}

export async function PUT(request: NextRequest, context: Params) {
  const originError = assertSameOrigin(request);

  if (originError) {
    return originError;
  }

  return proxyUserRequest(request, context);
}

export async function DELETE(request: NextRequest, context: Params) {
  const originError = assertSameOrigin(request);

  if (originError) {
    return originError;
  }

  return proxyUserRequest(request, context);
}
