/**
 * CORS Configuration Helper
 *
 * Provides secure CORS headers based on environment configuration.
 * Uses EDGE_FUNCTION_ALLOWED_ORIGINS environment variable to restrict origins.
 */

/**
 * Get CORS headers with allowed origins from environment
 *
 * @param requestOrigin - The Origin header from the request (optional)
 * @param additionalMethods - Additional HTTP methods to allow (default: GET, POST, OPTIONS)
 * @returns CORS headers object
 */
export function getCorsHeaders(requestOrigin?: string, additionalMethods: string[] = []): Record<string, string> {
  // Get allowed origins from environment variable
  // Format: comma-separated list, e.g., "https://shopcall.ai,http://192.168.2.112:8081"
  const allowedOriginsEnv = Deno.env.get('EDGE_FUNCTION_ALLOWED_ORIGINS') || '*';

  // Determine the Access-Control-Allow-Origin value
  let allowOrigin = '*';

  if (allowedOriginsEnv !== '*' && requestOrigin) {
    // Parse allowed origins
    const allowedOrigins = allowedOriginsEnv.split(',').map(o => o.trim());

    // Check if request origin is in allowed list
    if (allowedOrigins.includes(requestOrigin)) {
      allowOrigin = requestOrigin;
    } else {
      // Request origin not allowed - return first allowed origin as fallback
      // This will cause CORS error on browser side, which is expected behavior
      allowOrigin = allowedOrigins[0] || '*';
    }
  } else if (allowedOriginsEnv !== '*') {
    // No request origin provided, use first allowed origin
    const allowedOrigins = allowedOriginsEnv.split(',').map(o => o.trim());
    allowOrigin = allowedOrigins[0] || '*';
  }

  // IMPORTANT: Keep all these methods in the list!
  // DELETE is required for custom-content-delete and other delete operations.
  // PATCH is required for custom-urls and update operations.
  // Removing any method will cause CORS errors in the browser.
  const defaultMethods = [
    'GET',
    'POST',
    'PUT',
    'PATCH',
    'DELETE',
    'OPTIONS'
  ];
  const allMethods = [...new Set([...defaultMethods, ...additionalMethods])];

  return {
    'Access-Control-Allow-Origin': allowOrigin,
    'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
    'Access-Control-Allow-Methods': allMethods.join(', '),
  };
}

/**
 * Handle CORS preflight request
 *
 * @param requestOrigin - The Origin header from the request (optional)
 * @param additionalMethods - Additional HTTP methods to allow
 * @returns Response for OPTIONS request
 */
export function handleCorsPreflightRequest(requestOrigin?: string, additionalMethods: string[] = []): Response {
  return new Response(null, {
    headers: getCorsHeaders(requestOrigin, additionalMethods)
  });
}
