import { json } from "@remix-run/node";
import type { LoaderFunctionArgs } from "@remix-run/node";

export async function loader({ request }: LoaderFunctionArgs) {
  // Only allow this in development or if a special debug header is set
  const isDev = process.env.NODE_ENV === "development";
  const debugHeader = request.headers.get("x-debug-token");
  const debugToken = process.env.DEBUG_TOKEN;
  
  if (!isDev && (!debugToken || debugHeader !== debugToken)) {
    throw new Response("Not Found", { status: 404 });
  }

  // Safe environment info (no secrets)
  const envInfo = {
    NODE_ENV: process.env.NODE_ENV,
    GITHUB_APP_ID: process.env.GITHUB_APP_ID ? '✅ Set' : '❌ Missing',
    GITHUB_APP_NAME: process.env.GITHUB_APP_NAME ? '✅ Set' : '❌ Missing',
    GITHUB_APP_PRIVATE_KEY: process.env.GITHUB_APP_PRIVATE_KEY ? '✅ Set' : '❌ Missing',
    GITHUB_APP_CLIENT_ID: process.env.GITHUB_APP_CLIENT_ID ? `✅ Set (${process.env.GITHUB_APP_CLIENT_ID?.substring(0, 8)}...)` : '❌ Missing',
    GITHUB_APP_CLIENT_SECRET: process.env.GITHUB_APP_CLIENT_SECRET ? '✅ Set' : '❌ Missing',
    GITHUB_WEBHOOK_SECRET: process.env.GITHUB_WEBHOOK_SECRET ? '✅ Set' : '❌ Missing',
    GITHUB_CALLBACK_URL: process.env.GITHUB_CALLBACK_URL || '❌ Missing',
    SESSION_SECRET: process.env.SESSION_SECRET ? '✅ Set' : '❌ Missing',
  };

  return json({
    timestamp: new Date().toISOString(),
    environment: envInfo,
    request: {
      url: request.url,
      method: request.method,
      headers: Object.fromEntries(request.headers.entries()),
    }
  });
}
