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

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

  apply_server_side_encryption_by_default = {
    sse_algorithm = "AES256"
  }

  # only retain payloads for 180 days
  lifecycle_rules_options_current_version_expiration = [
    {
      prefix  = ""
      enabled = true
      days    = 180
    }
  ]

  lifecycle_rules_options_noncurrent_version_expiration = [
    {
      prefix  = ""
      enabled = true
      days    = 180
    }
  ]
}

data "aws_iam_policy_document" "s3_read_write_policy" {
  statement {
    actions = [
      "s3:GetObject",
      "s3:GetObject*",
      "s3:PutObject",
      "s3:PutObject*",
    ]

    resources = [
      "${module.s3_bucket.s3_bucket_arn_output}/*"
    ]
  }

  statement {
    actions = [
      "s3:GetBucketLocation",
      "s3:ListBucket",
    ]

    resources = [
      module.s3_bucket.s3_bucket_arn_output
    ]
  }
}

# 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 = data.aws_iam_policy_document.s3_read_write_policy.json
  tags = {
    environment        = var.environment
    service_name       = var.service_name
    application_family = var.application_family
    terraformed        = true
  }
}
