import { createServer, type Server } from 'http';

/** Build the redirect target from a PINNED host — never the request Host header. */
export function buildRedirectLocation(pinnedHost: string, httpsPort: number, reqUrl: string): string {
  const safePath = reqUrl.replace(/[\r\n ]/g, '');
  const hostPort = httpsPort === 443 ? pinnedHost : `${pinnedHost}:${httpsPort}`;
  return `https://${hostPort}${safePath.startsWith('/') ? safePath : `/${safePath}`}`;
}

export interface RedirectServerOpts {
  httpsPort: number;
  pinnedHost: string;
}

export function createHttpRedirectServer(opts: RedirectServerOpts): Server {
  return createServer((req, res) => {
    const location = buildRedirectLocation(opts.pinnedHost, opts.httpsPort, req.url ?? '/');
    res.writeHead(301, { Location: location });
    res.end();
  });
}
