# Deployment for Centralized Archival Setup ====================================

data "aws_availability_zones" "available" {
  state = "available"
}

locals {
  region_abbr = split("-", data.aws_availability_zones.available.zone_ids[0])[0]
}

module "context" {
  source  = "hcassc.jfrog.io/iac-tf-modules-virtual__shared/context/aws"
  version = "< 1.0"

  stack_name          = "archival-stack-baseline"
  application_name    = "need-to-fill"
  project             = "DC-Migration-Project"
  environment         = "prod"
  cost_center_opex    = "271"
  cost_center_capex   = "000"
  data_classification = "internal"
  availability_tier   = "tier-1"
  app_owner           = "Director IT Infrastructure and Platform Engineering"
  team                = "need-to-fill"
  assignment_group    = "need-to-fill"
  owner               = "need-to-fill"
  business_unit       = "Business Supporting Services"
}

# Archival buckets -------------------------------------------------------------
# One bucket per log source, per hca-archival-<region_abbr>-<source> naming standard.
# All 6 share the same lifecycle/retention/encryption/lock posture.

locals {
  archival_sources = [
    "vpc-flow",
    "tgw-flow",
    "guardduty",
    "waf",
    "route53",
    "elb",
  ]

  archival_lifecycle_rules = {
    archive = {
      enabled         = true
      expiration_days = 366
      transitions = [
        {
          days          = 90
          storage_class = "GLACIER"
        }
      ]
    }
  }
}

module "archival_bucket" {
  source   = "hcassc.jfrog.io/iac-tf-modules-virtual__shared/s3-bucket/aws"
  version  = "< 1.0"
  for_each = toset(local.archival_sources)

  bucket_name = "hca-archival-${local.region_abbr}-${each.key}"

  versioning_enabled = true

  object_lock_enabled = true
  object_lock_default_retention = {
    mode = "COMPLIANCE"
    days = 366
  }

  sse_algorithm = "aws:kms"
  kms_key_id    = null

  lifecycle_rules = local.archival_lifecycle_rules

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Sid       = "DenyDelete"
        Effect    = "Deny"
        Principal = "*"
        Action = [
          "s3:DeleteObject",
          "s3:DeleteObjectVersion",
          "s3:DeleteBucket",
        ]
        Resource = [
          "arn:aws:s3:::hca-archival-${local.region_abbr}-${each.key}",
          "arn:aws:s3:::hca-archival-${local.region_abbr}-${each.key}/*",
        ]
      }
    ]
  })

  tags = module.context.tags
}
