import { Middleware } from "rjweb-server";
import { env } from "../env";

const ALLOWED_ORIGINS = new Set([env.PP_BASE_URL]);

export const corsMiddleware = new Middleware<{}, {}>("CORS Middleware", "1.0.0")
  .httpRequest(async (_config, _server, _context, ctr) => {
    const origin = ctr.headers.get("origin") || "";
    if (ALLOWED_ORIGINS.has(origin) || env.NODE_ENV === "development") {
      ctr.headers.set("Access-Control-Allow-Origin", origin || "*");
      ctr.headers.set("Access-Control-Allow-Credentials", "true");
      ctr.headers.set("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS");
      ctr.headers.set("Access-Control-Allow-Headers", "Content-Type,Authorization,X-Requested-With");
    }
  })
  .export();
