import { defineMiddleware } from 'astro:middleware';
import { launchState, type LaunchState } from '@/server/env';

export function withLaunchRobotsHeader(response: Response, launchState: LaunchState): Response {
  if (launchState === 'live') return response;
  if (response.status === 101 || (response as { webSocket?: unknown }).webSocket != null) {
    return response;
  }

  const headers = new Headers(response.headers);
  headers.set('X-Robots-Tag', 'noindex, nofollow');
  return new Response(response.body, {
    status: response.status,
    statusText: response.statusText,
    headers,
  });
}

export const launchRobots = defineMiddleware(async (_context, next) =>
  withLaunchRobotsHeader((await next()) as Response, launchState),
);
