/**
 * HTTP utility functions
 */

/**
 * Escape HTML special characters to prevent XSS
 */
export function escapeHtml(unsafe: string): string {
  return unsafe
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
}

/**
 * JSON response helper
 */
export function jsonResponse<T>(
  data: T,
  status: number,
  headers: Record<string, string> = {}
): Response {
  return new Response(JSON.stringify(data), {
    status,
    headers: {
      'Content-Type': 'application/json',
      'Content-Security-Policy': "default-src 'none'",
      'X-Content-Type-Options': 'nosniff',
      'X-Frame-Options': 'DENY',
      'Strict-Transport-Security': 'max-age=31536000; includeSubDomains',
      'Cache-Control': 'no-store',
      ...headers,
    },
  });
}

/**
 * Create error response
 */
export function createErrorResponse(
  message: string,
  status: number,
  code?: string,
  corsHeaders: Record<string, string> = {}
): Response {
  return jsonResponse(
    {
      error: message,
      code: code || 'ERROR',
    },
    status,
    corsHeaders
  );
}

/**
 * Create success response
 */
export function createSuccessResponse<T>(
  data: T,
  status: number = 200,
  corsHeaders: Record<string, string> = {}
): Response {
  return jsonResponse(data, status, corsHeaders);
}

/**
 * Helper function to get allowed CORS origin
 */
export function getAllowedOrigin(request: Request): string {
  const allowedOrigins = [
    'https://server-recommend.kappa-d8e.workers.dev',
  ];
  const origin = request.headers.get('Origin');

  // If Origin is provided and matches allowed list, return it
  if (origin && allowedOrigins.includes(origin)) {
    return origin;
  }

  // For requests without Origin (non-browser: curl, API clients, server-to-server)
  // Return empty string - CORS headers won't be sent but request is still processed
  // This is safe because CORS only affects browser requests
  if (!origin) {
    return '';
  }

  // Origin provided but not in allowed list - return first allowed origin
  // Browser will block the response due to CORS mismatch
  return allowedOrigins[0];
}

/**
 * Validate request origin for sensitive endpoints (e.g., provision)
 * Only allows requests from *.kappa-d8e.workers.dev or worker-to-worker calls
 */
export function isAllowedProvisionOrigin(request: Request): boolean {
  const origin = request.headers.get('Origin');
  const referer = request.headers.get('Referer');

  // Allow worker-to-worker calls (Cloudflare adds this header)
  // Note: This header indicates the request came from another Cloudflare Worker
  const cfWorker = request.headers.get('CF-Worker');
  if (cfWorker) {
    return true;
  }

  // If no Origin header (server-to-server, curl, etc.) - check Referer or allow
  // For strict mode, you might want to reject these too
  if (!origin) {
    // Check Referer as fallback
    if (referer && referer.includes('.kappa-d8e.workers.dev')) {
      return true;
    }
    // Allow server-to-server for now (can be made stricter with API key)
    return true;
  }

  // Check if Origin is from allowed domain
  const allowedPattern = /^https:\/\/[a-zA-Z0-9-]+\.kappa-d8e\.workers\.dev$/;
  return allowedPattern.test(origin);
}
