{% set config = merged_configs.get('aws_vpc', {}) %}
{% set comments = compliance_comments.get('aws_vpc', []) %}
# ------------------------------------------------------------------------------
# VPC
# ------------------------------------------------------------------------------
{% for comment in comments %}
# {{ comment }}
{% endfor %}

resource "aws_vpc" "this" {
  cidr_block = "{{ config.get('cidr_block', '10.0.0.0/16') }}"

  enable_dns_support   = {{ config.get('enable_dns_support', true) | lower }}
  enable_dns_hostnames = {{ config.get('enable_dns_hostnames', true) | lower }}

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

resource "aws_flow_log" "this" {
  vpc_id                   = aws_vpc.this.id
  traffic_type             = "{{ config.get('flow_log_traffic_type', 'ALL') }}"
  log_destination_type     = "{{ config.get('flow_log_destination_type', 'cloud-watch-logs') }}"
  log_destination          = {{ config.get('flow_log_destination', 'aws_cloudwatch_log_group.vpc_flow.arn') }}
  iam_role_arn             = {{ config.get('flow_log_role_arn', 'null') }}
  max_aggregation_interval = {{ config.get('flow_log_max_aggregation_interval', 60) }}

  tags = {
    Name      = "{{ project_id }}-vpc-flow-log"
    ManagedBy = "complyform"
  }
}

resource "aws_cloudwatch_log_group" "vpc_flow" {
  name              = "/aws/vpc/{{ config.get('name', project_id ~ '-vpc') }}/flow-logs"
  retention_in_days = {{ config.get('log_retention_days', 90) }}
  kms_key_id        = {{ config.get('log_kms_key_id', 'null') }}

  tags = {
    Name      = "{{ project_id }}-vpc-flow-logs"
    ManagedBy = "complyform"
  }
}

resource "aws_default_security_group" "default" {
  vpc_id = aws_vpc.this.id

  # Compliance: restrict default security group to deny all traffic
  tags = {
    Name      = "{{ project_id }}-default-sg-restricted"
    ManagedBy = "complyform"
  }
}
