# Optional content-addressed blob storage for the data plane (datalake blobs
# plan §18.2). Every resource here is gated by `enable_blobs` (default false),
# so existing stacks plan as a no-op.
#
# The bucket is dedicated to blobs, so the plane runs with an empty
# BLOB_S3_PREFIX and every key lives under one of two fixed segments:
#   objects/<datalakeId>/sha256/<hex>   verified, committed bytes
#   staging/<datalakeId>/<uploadId>     in-flight uploads, never served
#
# Versioning is deliberately off (a purge is real erasure, plan Q4) and the
# bucket never has force_destroy: `personal-cloud destroy` empties it first.

locals {
  blobs_enabled = var.enable_blobs ? 1 : 0
}

resource "aws_s3_bucket" "blobs" {
  count = local.blobs_enabled

  bucket        = "${local.name_prefix}-blobs-${data.aws_caller_identity.current.account_id}-${var.region}"
  force_destroy = false
}

resource "aws_s3_bucket_public_access_block" "blobs" {
  count = local.blobs_enabled

  bucket = aws_s3_bucket.blobs[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" "blobs" {
  count = local.blobs_enabled

  bucket = aws_s3_bucket.blobs[0].id

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

# Backstop for the plane's reaper: abandoned staging objects expire after a
# day, and no incomplete multipart upload outlives a day anywhere in the bucket.
resource "aws_s3_bucket_lifecycle_configuration" "blobs" {
  count = local.blobs_enabled

  bucket = aws_s3_bucket.blobs[0].id

  rule {
    id     = "expire-staging"
    status = "Enabled"

    filter {
      prefix = "staging/"
    }

    expiration {
      days = 1
    }
  }

  rule {
    id     = "abort-incomplete-multipart"
    status = "Enabled"

    filter {}

    abort_incomplete_multipart_upload {
      days_after_initiation = 1
    }
  }
}

data "aws_iam_policy_document" "blobs_bucket" {
  count = local.blobs_enabled

  statement {
    sid     = "DenyInsecureTransport"
    effect  = "Deny"
    actions = ["s3:*"]
    resources = [
      aws_s3_bucket.blobs[0].arn,
      "${aws_s3_bucket.blobs[0].arn}/*",
    ]

    principals {
      type        = "*"
      identifiers = ["*"]
    }

    condition {
      test     = "Bool"
      variable = "aws:SecureTransport"
      values   = ["false"]
    }
  }
}

resource "aws_s3_bucket_policy" "blobs" {
  count = local.blobs_enabled

  bucket = aws_s3_bucket.blobs[0].id
  policy = data.aws_iam_policy_document.blobs_bucket[0].json

  # S3 rejects a policy write that races the public access block update.
  depends_on = [aws_s3_bucket_public_access_block.blobs]
}

# Inline on the plane task role. Object read/write/delete on both prefixes
# (CopyObject reads staging/ and writes objects/). ListBucket is kept so that
# HeadObject/GetObject on a missing key answer 404 rather than 403, and is
# confined to the same two prefixes so the role cannot enumerate anything else.
data "aws_iam_policy_document" "plane_blobs" {
  count = local.blobs_enabled

  statement {
    sid = "BlobObjects"
    actions = [
      "s3:GetObject",
      "s3:PutObject",
      "s3:DeleteObject",
    ]
    resources = [
      "${aws_s3_bucket.blobs[0].arn}/objects/*",
      "${aws_s3_bucket.blobs[0].arn}/staging/*",
    ]
  }

  statement {
    sid       = "BlobListPrefixes"
    actions   = ["s3:ListBucket"]
    resources = [aws_s3_bucket.blobs[0].arn]

    condition {
      test     = "StringLike"
      variable = "s3:prefix"
      values   = ["objects/*", "staging/*"]
    }
  }
}

resource "aws_iam_role_policy" "plane_blobs" {
  count = local.blobs_enabled

  name   = "${local.name_prefix}-plane-blobs"
  role   = aws_iam_role.plane_task.id
  policy = data.aws_iam_policy_document.plane_blobs[0].json
}

# Audit pseudonym key, separate from the token signing secret so that whoever
# analyzes audit pseudonyms cannot also mint data tokens (plan §19.1). The
# plane refuses to start with blobs enabled and no DATALAKE_AUDIT_SECRET.
resource "random_password" "audit_secret" {
  count = local.blobs_enabled

  length  = 64
  special = false
}

resource "aws_secretsmanager_secret" "audit" {
  count = local.blobs_enabled

  name        = "${local.name_prefix}/audit-secret"
  description = "Audit pseudonym key for the Aries datalake data plane"
  # Deleted immediately: `personal-cloud up --disable-blobs` destroys this
  # secret and a later `--blobs` recreates it under the same name, which a
  # pending (recovery-window) deletion would refuse. The key is regenerated
  # on every enable, so a recovery window would protect nothing.
  recovery_window_in_days = 0
}

resource "aws_secretsmanager_secret_version" "audit" {
  count = local.blobs_enabled

  secret_id     = aws_secretsmanager_secret.audit[0].id
  secret_string = random_password.audit_secret[0].result
}

locals {
  # Appended to the plane container definition (ecs.tf). Empty when blobs are
  # disabled, so the rendered task definition is unchanged. The catalog uses
  # the existing database: BLOB_DATABASE_URL is unset and falls back to the
  # DATABASE_URL secret.
  plane_blob_environment = var.enable_blobs ? [
    { name = "BLOB_STORE", value = "s3" },
    { name = "BLOB_S3_BUCKET", value = aws_s3_bucket.blobs[0].bucket },
    { name = "BLOB_MAX_BYTES", value = tostring(var.blob_max_bytes) },
    { name = "DATALAKE_AUDIT_SINK", value = "stdout" },
  ] : []

  plane_blob_secrets = [
    for secret in aws_secretsmanager_secret.audit : { name = "DATALAKE_AUDIT_SECRET", valueFrom = secret.arn }
  ]
}
