resource "terraform_data" "paid_resource_guard" {
  count = length(local.paid_component_requests) > 0 ? 1 : 0

  input = local.paid_component_requests

  lifecycle {
    precondition {
      condition     = var.permit_paid_resources
      error_message = "Set permit_paid_resources=true before enabling Aether paid components."
    }
  }
}

resource "aws_budgets_budget" "monthly" {
  count = var.enable_budget ? 1 : 0

  name         = "${local.name}-monthly"
  budget_type  = "COST"
  limit_amount = tostring(var.monthly_budget_usd)
  limit_unit   = "USD"
  time_unit    = "MONTHLY"

  dynamic "notification" {
    for_each = var.budget_alert_email == null ? [] : [var.budget_alert_email]

    content {
      comparison_operator        = "GREATER_THAN"
      notification_type          = "FORECASTED"
      subscriber_email_addresses = [notification.value]
      threshold                  = 80
      threshold_type             = "PERCENTAGE"
    }
  }
}

resource "aws_s3_bucket" "external_backup" {
  count = var.enable_external_backup_bucket ? 1 : 0

  bucket        = local.external_backup_bucket_name
  force_destroy = false

  tags = {
    Purpose = "external-backup-test"
  }

  depends_on = [terraform_data.paid_resource_guard]
}

resource "aws_s3_bucket_public_access_block" "external_backup" {
  count = var.enable_external_backup_bucket ? 1 : 0

  bucket                  = aws_s3_bucket.external_backup[0].id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

resource "aws_s3_bucket_server_side_encryption_configuration" "external_backup" {
  count = var.enable_external_backup_bucket ? 1 : 0

  bucket = aws_s3_bucket.external_backup[0].id

  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm = "AES256"
    }
  }
}

resource "aws_s3_bucket_versioning" "external_backup" {
  count = var.enable_external_backup_bucket ? 1 : 0

  bucket = aws_s3_bucket.external_backup[0].id

  versioning_configuration {
    status = "Enabled"
  }
}
