{% set config = merged_configs.get('aws_s3_bucket', {}) %}
{% set comments = compliance_comments.get('aws_s3_bucket', []) %}
# ------------------------------------------------------------------------------
# S3 Bucket with versioning and encryption
# ------------------------------------------------------------------------------
{% for comment in comments %}
# {{ comment }}
{% endfor %}

resource "aws_s3_bucket" "this" {
  bucket = "{{ config.get('bucket', project_id ~ '-bucket') }}"

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

resource "aws_s3_bucket_versioning" "this" {
  bucket = aws_s3_bucket.this.id

  versioning_configuration {
    status = "{{ config.get('versioning_status', 'Enabled') }}"
  }
}

resource "aws_s3_bucket_server_side_encryption_configuration" "this" {
  bucket = aws_s3_bucket.this.id

  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm     = "{{ config.get('sse_algorithm', 'aws:kms') }}"
      kms_master_key_id = {{ config.get('kms_master_key_id', 'null') }}
    }
    bucket_key_enabled = {{ config.get('bucket_key_enabled', true) | lower }}
  }
}

resource "aws_s3_bucket_public_access_block" "this" {
  bucket = aws_s3_bucket.this.id

  block_public_acls       = {{ config.get('block_public_acls', true) | lower }}
  block_public_policy     = {{ config.get('block_public_policy', true) | lower }}
  ignore_public_acls      = {{ config.get('ignore_public_acls', true) | lower }}
  restrict_public_buckets = {{ config.get('restrict_public_buckets', true) | lower }}
}

resource "aws_s3_bucket_logging" "this" {
  bucket = aws_s3_bucket.this.id

  target_bucket = "{{ config.get('logging_target_bucket', project_id ~ '-logs') }}"
  target_prefix = "{{ config.get('logging_target_prefix', 's3-access-logs/') }}"
}

{% if config.get('lifecycle_rules') %}
resource "aws_s3_bucket_lifecycle_configuration" "this" {
  bucket = aws_s3_bucket.this.id

  {% for rule in config.get('lifecycle_rules', []) %}
  rule {
    id     = "{{ rule.get('id', 'rule-' ~ loop.index) }}"
    status = "{{ rule.get('status', 'Enabled') }}"

    {% if rule.get('transition_days') %}
    transition {
      days          = {{ rule.transition_days }}
      storage_class = "{{ rule.get('storage_class', 'STANDARD_IA') }}"
    }
    {% endif %}

    {% if rule.get('expiration_days') %}
    expiration {
      days = {{ rule.expiration_days }}
    }
    {% endif %}
  }
  {% endfor %}
}
{% endif %}
