module "throttler_manager_fargate_environment" {
  source = "git@github.com:theorchard/terraform-fargate.git//?ref=1.7.6"

  aws_region                        = var.aws_region
  environment                       = var.environment
  service_name                      = var.throttler_manager_service_name
  task_type                         = "worker"
  task_cpu                          = var.throttler_manager_fargate_task_cpu
  task_memory                       = var.throttler_manager_fargate_task_memory
  desired_task_count                = 0
  minimum_capacity                  = 0
  maximum_capacity                  = 1
  autoscaling_cpu_policy_enabled    = false
  autoscaling_memory_policy_enabled = false
  health_check_command              = "true"
  vpc_id                            = "vpc-7f0e841a"

  cloudwatch_event_enabled  = true
  cloudwatch_event_schedule = var.throttler_manager_fargate_cloudwatch_event_schedule
  fargate_service_subnets   = var.throttler_manager_fargate_subnet_ids

  iam_managed_policy_attachments = [
    aws_iam_policy.throttler_manager_task_policy.arn
  ]

  environment_variables = [
    {
      Environment = var.environment
    },
    {
      LOGGER_DSN = var.LOGGER_DSN
    },
    {
      SENTRY_DSN = data.aws_secretsmanager_secret_version.throttler_manager_sentry_dsn.secret_string
    },
  ]
}

resource "aws_iam_policy" "throttler_manager_task_policy" {
  name   = "${var.environment}-${var.throttler_manager_service_name}-task-policy"
  policy = data.aws_iam_policy_document.throttler_manager_task_policy.json
}

data "aws_iam_policy_document" "throttler_manager_task_policy" {
  statement {
    effect = "Allow"
    actions = [
      "sqs:GetQueueAttributes",
      "sqs:GetQueueUrl",
      "sqs:ListQueueTags",
      "sqs:ListQueues",
      "sqs:TagQueue",
      "sqs:UntagQueue"
    ]
    resources = [
      "arn:aws:sqs:*"
    ]
  }

  statement {
    effect = "Allow"
    actions = [
      "lambda:InvokeFunction"
    ]
    resources = [
      module.throttler_lambda.lambda_arn
    ]
  }
}
