locals {
  name = "${var.env_prefix}-${var.project_group}-${var.project}"
}


# ECS Service
resource "aws_ecs_service" "main" {
  name                               = local.name
  cluster                            = var.cluster_arn
  task_definition                    = module.task_definition_main.ecs_task_definition.arn
  desired_count                      = var.task_count
  enable_ecs_managed_tags            = true
  propagate_tags                     = "TASK_DEFINITION"
  deployment_minimum_healthy_percent = 0
  deployment_maximum_percent         = 100

  network_configuration {
    subnets          = var.subnets
    security_groups  = var.security_groups
    assign_public_ip = var.is_public
  }

  dynamic "capacity_provider_strategy" {
    for_each = var.capacity_provider_strategy
    content {
      base              = lookup(capacity_provider_strategy.value, "base", 0)
      capacity_provider = lookup(capacity_provider_strategy.value, "capacity_provider", "FARGATE")
      weight            = lookup(capacity_provider_strategy.value, "weight", 1)
    }
  }

  wait_for_steady_state = var.wait_for_steady_state

  lifecycle {
    ignore_changes = [desired_count]
  }
}

module "task_definition_main" {
  source = "../../../ecs/tasks/fargate_v2"

  # task definition
  env_prefix         = var.env_prefix
  cpu                = var.cpu
  memory             = var.memory
  project            = var.project
  project_group      = var.project_group
  task_exec_role_arn = var.task_exec_role_arn
  task_family        = local.name
  task_role_arn      = var.task_role_arn
  common_tags        = var.common_tags

  # container definition
  secrets              = var.secrets
  region               = var.region
  image                = var.image
  env_vars             = var.env_vars
  port_mapping_enabled = false
  command              = var.command
  retention_in_days    = var.retention_in_days
}
