{% for secret in resources -%}
resource "aws_secretsmanager_secret" "secret_{{ secret.name_sanitized }}" {
  name = "{{ secret.Name }}"

  {%- if secret.get('Description') %}
  description = "{{ secret.Description }}"
  {%- endif %}

  {%- if secret.kms_encrypted %}
  kms_key_id = "{{ secret.kms_key_id }}"
  {%- endif %}

  {%- if secret.get('replica_regions_formatted') %}
  {%- for replica in secret.replica_regions_formatted %}
  replica {
    region = "{{ replica.region }}"
    {%- if replica.get('kms_key_id') %}
    kms_key_id = "{{ replica.kms_key_id }}"
    {%- endif %}
  }
  {%- endfor %}
  {%- endif %}

  {%- if secret.rotation_enabled %}
  # Automatic rotation configuration
  {%- if secret.get('rotation_rules_formatted') and secret.rotation_rules_formatted.get('automatically_after_days') %}
  rotation_lambda_arn = "{{ secret.rotation_lambda_arn }}"
  rotation_rules {
    automatically_after_days = {{ secret.rotation_rules_formatted.automatically_after_days }}
  }
  {%- endif %}
  {%- endif %}

  recovery_window_in_days = {{ 30 if not secret.is_deleted else 0 }}

  tags = {
    {%- for key, value in secret.get('tags_formatted', {}).items() -%}
    "{{ key }}" = "{{ value }}"
    {%- endfor %}
    "SecretType" = "{{ secret.secret_type }}"
    {%- if secret.is_aws_managed %}
    "ManagedBy" = "{{ secret.OwningService }}"
    {%- endif %}
  }

  {%- if secret.is_deleted %}
  # This secret is marked for deletion
  lifecycle {
    prevent_destroy = false
  }
  {%- else %}
  lifecycle {
    prevent_destroy = true
  }
  {%- endif %}
}

{%- if secret.get('resource_policy') %}
# Resource policy for {{ secret.Name }}
resource "aws_secretsmanager_secret_policy" "policy_{{ secret.name_sanitized }}" {
  secret_arn = aws_secretsmanager_secret.secret_{{ secret.name_sanitized }}.arn
  policy     = jsonencode({{ secret.resource_policy | tojson | safe }})
}
{%- endif %}

{%- if not secret.is_aws_managed %}
# Secret version - Note: Actual secret value must be managed outside Terraform
resource "aws_secretsmanager_secret_version" "version_{{ secret.name_sanitized }}" {
  secret_id = aws_secretsmanager_secret.secret_{{ secret.name_sanitized }}.id
  
  # The secret_string value should be managed outside of Terraform
  # for security reasons. This is a placeholder.
  secret_string = jsonencode({
    # Replace with actual secret structure
    "placeholder" = "value_managed_outside_terraform"
  })

  lifecycle {
    ignore_changes = [
      secret_string,
      secret_binary,
    ]
  }
}
{%- endif %}

{%- if not loop.last %}

{% endif %}
{%- endfor %}