################
# Snowflake — Decentralized RBAC (Agent-Consumable Views)
################
# Snowflake roles and service users are defined in:
#   prod/snowflake/orchard/roles/variables.tf       — QA/PROD_CODA_SVC, QA/PROD_CODA_SEARCH_SVC
#   prod/snowflake/orchard/service_users/variables.tf — corresponding _USER entries
# Secure views and database roles are managed in the database repo.
#
# This file wires the AWS side: Secrets Manager entries for RSA private keys
# and IAM policies so Fargate tasks can read them at runtime.

################
# Secrets — Snowflake private key for the main coda app
################

# Snowflake private key for the QA_CODA_SVC_USER service account.
# Key-pair auth only — no password. Rotated every 90 days via automation.
module "ows_coda_snowflake_secrets" {
  source = "git@github.com:theorchard/terraform-secrets-manager.git//?ref=1.6.1"
  for_each = local.is_ephemeral ? toset([]) : toset([
    "SNOWFLAKE_PRIVATE_KEY",
    "SNOWFLAKE_PRIVATE_KEY_PASS",
  ])

  application_family = var.application_family
  environment        = var.environment
  service_name       = var.service_name
  secret_name        = each.value
}

################
# IAM — Snowflake secrets access for the main coda Fargate task
################

# Grant the Fargate task role permission to read Snowflake secrets at runtime.
resource "aws_iam_role_policy" "ows_coda_snowflake_secrets_read" {
  count = local.is_ephemeral ? 0 : 1

  name = "${var.environment}-${local.service_label}-snowflake-secrets-read"
  role = module.ows_coda_fargate_environment.fargate_task_iam_role_name

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Effect = "Allow"
        Action = [
          "secretsmanager:GetSecretValue",
          "secretsmanager:DescribeSecret"
        ]
        Resource = "arn:aws:secretsmanager:${var.region}:${data.aws_caller_identity.current.account_id}:secret:${var.environment}/${var.service_name}/SNOWFLAKE_*"
      }
    ]
  })
}
