# Resources associated with applying the refresh data for QA via PDP Backfill ECS Task
locals {
  container_name = "pdp-backfill"
  ecs_task       = "${var.environment}-${local.container_name}"
}

data "aws_ecs_task_definition" "pdp_backfill_task_definition" {
  task_definition = local.ecs_task
}

data "aws_ecs_cluster" "pdp_backfill_cluster" {
  cluster_name = local.ecs_task
}

data "aws_security_group" "pdp_backfill_task_sg" {
  name = "${local.ecs_task}-task-security-group"
}

# Reference the policy that allows running the qa-pdp-backfill ECS task
data "aws_iam_policy" "pdp_backfill_run_task_policy" {
  name = "${var.environment}-${local.container_name}-run-task-policy"
}

module "vpc_info" {
  source      = "git@github.com:theorchard/terraform-vpc-info.git?ref=3.1.0"
  environment = var.environment
}

# AWS Step Function-specific policy for running qa-pdp-backfill ECS task
# Assume the more ecs-y policy is already provided by data.aws_iam_policy.pdp_backfill_run_task_policy
data "aws_iam_policy_document" "sfn_run_pdp_backfill_task" {
  statement {
    effect = "Allow"
    actions = [
      "ecs:StopTask"
    ]
    resources = [
      "arn:aws:ecs:${var.aws_region}:${data.aws_caller_identity.current.account_id}:task/${var.environment}-pdp-backfill/*",
    ]
  }

  statement {
    effect = "Allow"
    actions = [
      "events:PutTargets",
      "events:PutRule",
      "events:DescribeRule"
    ]
    resources = [
      "arn:aws:events:${var.aws_region}:${data.aws_caller_identity.current.account_id}:rule/StepFunctionsGetEventsForECSTaskRule"
    ]
  }
}


# Attach to Run ECS Task policy to the role created for the Step Function
resource "aws_iam_role_policy" "sfn_dynamodb_refresh_run_pdp_backfill_policy" {
  name   = "${var.environment}-${var.service_name}-sfn-run-pdp-backfill-policy"
  role   = aws_iam_role.sfn_dynamodb_refresh_role.id
  policy = data.aws_iam_policy_document.sfn_run_pdp_backfill_task.json
}

# Attach the policy so Eventbridge can run the pdp-backfill ECS task
resource "aws_iam_role_policy_attachment" "sfn_dynamodb_refresh_run_pdp_backfill_fargate_policy" {
  role       = aws_iam_role.sfn_dynamodb_refresh_role.id
  policy_arn = data.aws_iam_policy.pdp_backfill_run_task_policy.arn
}
