# Dynamically build S3 resources list from bucket ARNs and resource paths
locals {
  # Generate full resource ARNs by combining bucket ARNs with resource paths
  resources = flatten([
    for bucket_arn in var.bucket_arns : concat(
      [bucket_arn],  # bare ARN for bucket-level actions like ListBucket
      [for path in var.resource_paths : "${bucket_arn}${path}"]
    )
  ])
}

# IAM Policy with dynamic actions and resources
resource "aws_iam_policy" "s3_policy" {
  name        = var.policy_name
  description = var.policy_description

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      merge(
        {
          Effect   = "Allow"
          Action   = var.actions
          Resource = local.resources
        },
        var.conditions != null ? { Condition = var.conditions } : {}
      )
    ]
  })

  tags = var.tags
}
