# CORS configuration for MetaMask integration
# This ensures MetaMask and Portfolio can access RPC and explorer endpoints

resource "azurerm_application_gateway" "main" {
  # ... existing configuration ...
  
  # HTTP listener with CORS support
  http_listener {
    name                           = "rpc-https-listener"
    frontend_ip_configuration_name = "public-ip"
    frontend_port_name             = "https"
    protocol                       = "Https"
    ssl_certificate_name           = "ssl-certificate"
    
    # CORS configuration
    custom_error_configuration {
      status_code           = "HttpStatus403"
      custom_error_page_url = "https://explorer.d-bis.org/errors/403.html"
    }
  }
  
  # Backend HTTP settings with CORS headers
  backend_http_settings {
    name                  = "rpc-backend-settings"
    cookie_based_affinity = "Disabled"
    port                  = 8545
    protocol              = "Http"
    request_timeout       = 60
    
    # CORS headers (configured via rewrite rule set)
    probe_name = "rpc-health-probe"
  }
  
  # Rewrite rule set for CORS headers
  rewrite_rule_set {
    name = "cors-headers"
    
    rewrite_rule {
      name          = "add-cors-headers"
      rule_sequence = 100
      
      response_header_configuration {
        header_name  = "Access-Control-Allow-Origin"
        header_value = "*" # In production, restrict to specific origins
      }
      
      response_header_configuration {
        header_name  = "Access-Control-Allow-Methods"
        header_value = "GET, POST, OPTIONS"
      }
      
      response_header_configuration {
        header_name  = "Access-Control-Allow-Headers"
        header_value = "Content-Type, Authorization"
      }
      
      response_header_configuration {
        header_name  = "Access-Control-Max-Age"
        header_value = "3600"
      }
    }
  }
  
  # Request routing rule
  request_routing_rule {
    name                        = "rpc-https-rule"
    rule_type                   = "Basic"
    http_listener_name          = "rpc-https-listener"
    backend_address_pool_name   = "rpc-backend-pool"
    backend_http_settings_name  = "rpc-backend-settings"
    rewrite_rule_set_name       = "cors-headers"
  }
}

# Note: This is a template. Adjust based on your actual Application Gateway configuration.
# CORS headers should be added to response headers for RPC and explorer endpoints.

