terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}

variable "eks_oidc" {
  description = "OIDC provider URL without shcema (https://) for the EKS cluster"
  type        = string
}

variable "env" {
  description = "Environment for the deployment: dev, prod, staging"
  type        = string
}

variable "logical_region_name" {
  description = "Logical name of the region, used for naming resources"
  type        = string
}

variable "controlplane_account" {
  description = "AWS account ID of the control plane"
  type        = string
}

variable "dataplane_accounts" {
  description = "List of AWS account IDs that will be managed by the dataplane manager"
  type        = list(string)
}

variable "is_byoc" {
  description = "Flag to indicate if this is a BYOC (Bring Your Own Control Plane) deployment"
  type        = bool
  default     = false
}

variable "dataplane_role_name" {
  description = "Dataplane assumed role name for dataplane manager"
  type        = string
  default     = "tidbcloud-dataplane-manager-assumed-role"
}

variable "metering_read_write_role_arn" {
  description = "The ARN of the metering read-write role"
  type        = string
  default     = ""
}

variable "billing_sqs_arn" {
  type    = string
  default = "*"
}

variable "auto_deploy_owner_tag" {
  type = string
}

locals {
  send_sqs_permission = [{
    Action = [
      "sqs:SendMessage"
    ],
    Effect = "Allow",
    Resource = [
      var.billing_sqs_arn,
    ],
    Sid = "SendSQS"
  }]

  byoc_control_permission_policy = [
    {
      Action = [
        "ec2:DescribeVpcs",
        "ec2:DescribeVpcAttribute",
        "ec2:DescribeVpcEndpoints",
        "ec2:DescribeVpcEndpointConnections",
        "ec2:DescribeVpcEndpointServices",
        "ec2:DescribeVpcEndpointServicePermissions",
        "ec2:DescribeVpcEndpointServiceConfigurations",
        "ec2:DescribeAddresses",
        "ec2:DescribeSubnets",
        "ec2:DescribeRouteTables",
        "ec2:DescribeNatGateways",
        "ec2:DescribeInternetGateways",
        "ec2:DescribeSecurityGroup*",
        "ec2:DescribeLaunchTemplates",
        "ec2:DescribeLaunchTemplateVersions",
        "ec2:DescribeInstances",
        "ec2:DescribeInstanceAttribute",
        "ec2:DescribeInstanceTypes",
        "ec2:DescribeAvailabilityZones",
        "ec2:DescribeAddressesAttribute",
        "ec2:DescribePrefixLists",
        "ec2:DescribeNetworkInterfaces"
      ],
      Effect   = "Allow",
      Resource = "*",
      Sid      = "EC2ReadOnlyOperations"
    },
    {
      Action = [
        "ec2:CreateVpc",
        "ec2:ModifyVpc*",
        "ec2:CreateVpcEndpointServiceConfiguration",
        "ec2:DeleteVpcEndpointServiceConfigurations",
        "ec2:CreateVpcEndpoint",
        "ec2:DeleteVpcEndpoints",
        "ec2:DeleteVpc",
        "ec2:AllocateAddress",
        "ec2:ReleaseAddress",
        "ec2:CreateNatGateway",
        "ec2:CreateInternetGateway",
        "ec2:CreateSubnet",
        "ec2:CreateSecurityGroup",
        "ec2:CreateLaunchTemplate",
        "ec2:DeleteLaunchTemplate",
        "ec2:AuthorizeSecurityGroupIngress",
        "ec2:AuthorizeSecurityGroupEgress",
        "ec2:CreateRouteTable",
        "ec2:CreateRoute",
        "ec2:AttachInternetGateway",
        "ec2:DetachInternetGateway",
        "ec2:AssociateNatGatewayAddress",
        "ec2:AssociateRouteTable",
        "ec2:DisassociateRouteTable",
        "ec2:AcceptVpcEndpointConnections",
        "ec2:RejectVpcEndpointConnections",
        "ec2:StartVpcEndpointServicePrivateDnsVerification",
        "ec2:RevokeSecurityGroupIngress",
        "ec2:DeleteSecurityGroup",
        "ec2:DeleteRouteTable",
        "ec2:DeleteNatGateway",
        "ec2:RunInstances",
        "ec2:DeleteInternetGateway",
        "ec2:DeleteSubnet",
        "ec2:CreateTags",
        "ec2:DeleteTags",
        "ec2:CreateLaunchTemplateVersion",
        "ec2:RevokeSecurityGroupEgress"
      ],
      Effect   = "Allow",
      Resource = "*",
      Sid      = "EC2WriteOperationsRegionRestricted"
    }
  ]
  premium_control_permission_policy = [
    {
      Action = [
        "route53:ListResourceRecordSets",
        "route53:ChangeResourceRecordSets",
        "route53:AssociateVPCWithHostedZone",
        "route53:GetHostedZone",
        "route53:GetChange"
      ],
      Effect   = "Allow",
      Resource = "*",
      Sid      = "Route53ResourceRecordSetOperations"
    }
  ]
}

module "dataplane_manager" {
  source = "../../iam-controlplane"

  controlplane_account = var.controlplane_account
  oidc                 = var.eks_oidc
  role_name            = "${var.env}-${var.logical_region_name}-dataplane-manager"
  service_account      = "dataplane-manager,aws-provider,cluster-ng-server,o11y-agent-control-server,ticdc-service,nextgen-metering-server-manager"
  policy_document = jsonencode({
    Version = "2012-10-17"
    Statement = concat([
      {
        Action = "sts:AssumeRole"
        Effect = "Allow"
        Resource = concat(
          [for acct in var.dataplane_accounts : "arn:aws:iam::${acct}:role/${var.dataplane_role_name}"],
          var.metering_read_write_role_arn == "" ? [] : [var.metering_read_write_role_arn]
        )
      }
      ],
      local.send_sqs_permission,
      var.is_byoc ? local.byoc_control_permission_policy : local.premium_control_permission_policy
    )
  })
  auto_deploy_owner_tag = var.auto_deploy_owner_tag
}

output "role_arn" {
  value = module.dataplane_manager.controlplane_role_arn
}

