variable "oidc_arn" {
  type        = string
  description = "AWS OIDC provider ARN for the Azure AKS cluster"
}

variable "env" {
  type = string
}

variable "logical_region_name" {
  type = string
}

variable "auto_deploy_owner_tag" {
  type = string
}

locals {
  # billing-sqs-dev-reporter does not exist; fall back to staging policy for dev
  billing_sqs_policy_env = var.env == "dev" ? "staging" : var.env
}

data "aws_caller_identity" "current" {}

resource "aws_iam_role" "billing_reporter" {
  name = "azure-${var.logical_region_name}-billing-${var.env}-reporter"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Effect = "Allow"
        Action = "sts:AssumeRoleWithWebIdentity"
        Principal = {
          Federated = var.oidc_arn
        }
        Condition = {
          StringEquals = {
            "${split("oidc-provider/", var.oidc_arn)[1]}:aud" = "sts.amazonaws.com"
          }
        }
      }
    ]
  })

  tags = {
    "tidbcloud-auto-deploy-owner" = var.auto_deploy_owner_tag
  }
}

resource "aws_iam_role_policy_attachment" "billing_reporter" {
  role       = aws_iam_role.billing_reporter.name
  policy_arn = "arn:aws:iam::${data.aws_caller_identity.current.account_id}:policy/billing-sqs-${local.billing_sqs_policy_env}-reporter"
}

output "role_arn" {
  value = aws_iam_role.billing_reporter.arn
}

output "role_name" {
  value = aws_iam_role.billing_reporter.name
}
