variable "ecs_cluster" {}
variable "task_role_arn" {}
variable "execution_role_arn" {}
variable "stage" {}
variable "job_name" {}
variable "schedule" { default = "rate(1 hour)" }
variable "use_schedule" { default = true }
variable "cpu" { default = 2048 }
variable "memory" { default = 8192 }



resource "aws_ecs_task_definition" "background_taskdef" {

  family                = replace("${var.job_name}_${var.stage}", "-", "_")
  container_definitions = replace(replace(file("./background-taskdef.json"), "STAGE", var.stage), "JOBX", var.job_name)
  memory = var.memory
  cpu = var.cpu
  network_mode = "awsvpc"
  requires_compatibilities = ["FARGATE"]
  execution_role_arn = var.execution_role_arn
  task_role_arn = var.task_role_arn
}

resource "aws_cloudwatch_event_rule" "schedule" {
  count = var.use_schedule ? 1 : 0 
  name        = "${var.job_name}-schedule"
  schedule_expression = "${var.schedule}"
}



resource "aws_cloudwatch_event_target" "job_target" {
  count = var.use_schedule ? 1 : 0 
  target_id = "${var.job_name}"
  arn       = var.ecs_cluster
  rule      = aws_cloudwatch_event_rule.schedule[0].name
  role_arn  = "arn:aws:iam::679918342773:role/service-role/Amazon_EventBridge_Invoke_ECS_1758992733"

  ecs_target {
    task_count          = 1
   launch_type                        = "" 

   # capacity_provider_strategy = [{capacity_provider = "FARGATE_SPOT"}]
    task_definition_arn = aws_ecs_task_definition.background_taskdef.arn
    network_configuration {
      assign_public_ip = true
      security_groups  = [ "sg-004e5855310c453a3", "sg-02d167406b1082698"]
      subnets          = [ "subnet-5e675761", "subnet-8519fde2", "subnet-89bab8d4" ] 
    }
  }
}
