resource "aws_iam_user" "github_actions" {
  count = var.environment == "dev" ? 1 : 0
  name  = "github-actions-jiraport-deployer"
  path  = "/"
}

data "aws_iam_user" "existing_github_actions" {
  count     = var.environment != "dev" ? 1 : 0
  user_name = "github-actions-jiraport-deployer"
}

resource "aws_iam_access_key" "github_actions" {
  count = var.environment == "dev" ? 1 : 0
  user  = aws_iam_user.github_actions[0].name
}

resource "aws_iam_user_policy_attachment" "github_actions_ecr" {
  count      = var.environment == "dev" ? 1 : 0
  user       = aws_iam_user.github_actions[0].name
  policy_arn = "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryFullAccess"
}

resource "aws_iam_user_policy_attachment" "github_actions_eks_cluster" {
  count      = var.environment == "dev" ? 1 : 0
  user       = aws_iam_user.github_actions[0].name
  policy_arn = "arn:aws:iam::aws:policy/AmazonEKSClusterPolicy"
}

resource "aws_iam_user_policy" "github_actions_eks" {
  count = var.environment == "dev" ? 1 : 0
  name  = "github-actions-eks-policy"
  user  = aws_iam_user.github_actions[0].name

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = [
          "eks:DescribeCluster",
          "eks:ListClusters"
        ]
        Effect   = "Allow"
        Resource = "*"
      },
    ]
  })
}

output "github_actions_access_key_id" {
  value = var.environment == "dev" ? aws_iam_access_key.github_actions[0].id : null
}

output "github_actions_secret_access_key" {
  value     = var.environment == "dev" ? aws_iam_access_key.github_actions[0].secret : null
  sensitive = true
}

output "github_actions_user_arn" {
  value = var.environment == "dev" ? aws_iam_user.github_actions[0].arn : data.aws_iam_user.existing_github_actions[0].arn
}
