
module "s3_bucket" {
  source = "git@github.com:theorchard/terraform-s3.git//modules/s3_bucket?ref=3.15.1"

  env                = var.environment
  bucket_name        = var.bucket_name
  application_family = var.application_family

  apply_server_side_encryption_by_default = {
    sse_algorithm = "AES256"
  }

  # Mark current version of objects (under results only) to expire after 7 days.
  lifecycle_rules_options_current_version_expiration = [
    {
      prefix  = "auto-approve-sfn/results"
      enabled = true
      days    = 7
    }
  ]


  # Once object is updated, mark the historic version to expire after 7 days.
  lifecycle_rules_options_noncurrent_version_expiration = [
    {
      prefix  = "auto-approve-sfn"
      enabled = true
      days    = 7
    }
  ]
}

module "s3_read_write_policy" {
  source = "git@github.com:theorchard/terraform-iam-policy-templates.git//documents/s3/buckets_with_prefixes?ref=0.4.0"

  buckets = [{
    bucket = module.s3_bucket.s3_bucket_name_output
  }]
  action_types = ["read", "write"]
}

# Create policy for read-write access to the S3 bucket
resource "aws_iam_policy" "s3_read_write_policy" {
  name   = "S3-${var.environment}-${var.bucket_name}-RW"
  policy = module.s3_read_write_policy.policy.json
}

resource "aws_s3_bucket_notification" "bucket_notification" {
  bucket      = module.s3_bucket.s3_bucket_name_output
  eventbridge = true
}

