/**
 * Forward /.well-known/openid-configuration to the oidc-provider.
 *
 * The provider generates this discovery document automatically, but since the
 * catch-all route is mounted under /oidc/, requests to /.well-known/ need
 * explicit forwarding.
 */
import { getOidcProvider } from "../../utils/oidc-provider.js";

export default defineEventHandler(async (event) => {
  const provider = await getOidcProvider();
  const { req, res } = event.node;

  // The provider expects the path relative to its root
  req.url = "/.well-known/openid-configuration";

  // Traefik terminates TLS — tell the provider we're on https
  req.headers["x-forwarded-proto"] = "https";

  const callback = provider.callback() as Function;
  await new Promise<void>((resolve, reject) => {
    callback(req, res, (err: unknown) => {
      if (err) reject(err);
      else resolve();
    });
  });
});
