{% set config = merged_configs.get('aws_apigatewayv2_api', {}) %}
{% set comments = compliance_comments.get('aws_apigatewayv2_api', []) %}
# ------------------------------------------------------------------------------
# API Gateway v2 (HTTP API)
# ------------------------------------------------------------------------------
{% for comment in comments %}
# {{ comment }}
{% endfor %}

resource "aws_apigatewayv2_api" "this" {
  name          = "{{ config.get('name', project_id ~ '-api') }}"
  protocol_type = "{{ config.get('protocol_type', 'HTTP') }}"
  description   = "{{ config.get('description', 'Managed by ComplyForm') }}"

  {% if config.get('cors_configuration') %}
  cors_configuration {
    allow_headers  = {{ config.get('cors_allow_headers', '["content-type", "authorization"]') }}
    allow_methods  = {{ config.get('cors_allow_methods', '["GET", "POST", "PUT", "DELETE", "OPTIONS"]') }}
    allow_origins  = {{ config.get('cors_allow_origins', '["*"]') }}
    max_age        = {{ config.get('cors_max_age', 300) }}
  }
  {% endif %}

  disable_execute_api_endpoint = {{ config.get('disable_execute_api_endpoint', false) | lower }}

  tags = {
    Name      = "{{ config.get('name', project_id ~ '-api') }}"
    ManagedBy = "complyform"
  }
}

resource "aws_apigatewayv2_stage" "this" {
  api_id      = aws_apigatewayv2_api.this.id
  name        = "{{ config.get('stage_name', '$default') }}"
  auto_deploy = {{ config.get('auto_deploy', true) | lower }}

  access_log_settings {
    destination_arn = aws_cloudwatch_log_group.api_gw.arn
  }

  default_route_settings {
    throttling_burst_limit = {{ config.get('throttling_burst_limit', 100) }}
    throttling_rate_limit  = {{ config.get('throttling_rate_limit', 50) }}
  }

  tags = {
    Name      = "{{ project_id }}-api-stage"
    ManagedBy = "complyform"
  }
}

resource "aws_cloudwatch_log_group" "api_gw" {
  name              = "/aws/apigateway/{{ config.get('name', project_id ~ '-api') }}"
  retention_in_days = {{ config.get('log_retention_days', 90) }}
  kms_key_id        = {{ config.get('log_kms_key_id', 'null') }}

  tags = {
    Name      = "{{ project_id }}-api-gw-logs"
    ManagedBy = "complyform"
  }
}
