
locals {
  suffix         = substr(random_string.tg_id.result, 0, 5)
  name           = "${var.env_prefix}-${var.project_group}-${var.project}"
  tg_name        = length("${local.name}-${local.suffix}") > 32 ? "${var.env_prefix}-${var.project_group}-${random_string.tg_id.result}" : "${local.name}-${local.suffix}"
  abl_enabled    = var.alb_enabled ? ["Enabled"] : []
  sd_enabled     = var.sd_enabled ? ["Enabled"] : []
  container_name = var.container_name == "" ? var.project : var.container_name
}

resource "random_string" "tg_id" {
  length  = 16
  special = false
}

# Target group for ECS service
resource "aws_lb_target_group" "main" {
  count = var.alb_enabled ? 1 : 0

  name                 = local.tg_name
  port                 = var.tg_port
  protocol             = "HTTP"
  vpc_id               = var.vpc_id
  deregistration_delay = var.tg_deregistration_delay
  target_type          = "ip"

  health_check {
    path                = var.tg_health_check_path
    port                = var.tg_health_check_port
    protocol            = "HTTP"
    matcher             = var.tg_health_check_matcher
    interval            = var.tg_health_check_interval
    timeout             = var.tg_health_check_timeout
    unhealthy_threshold = var.tg_unhealthy_threshold
    healthy_threshold   = var.tg_healthy_threshold
  }

  tags = var.common_tags

  # fixes: Error deleting Target Group: ResourceInUse
  lifecycle {
    create_before_destroy = true
    ignore_changes        = [name]
  }
}

# ALB rules for
module "alb_rules" {
  count  = var.alb_enabled ? 1 : 0
  source = "../../../ec2/alb/https_rule_with_redirect"

  https_listener_arn = var.https_listener_arn
  tg_arn             = join("", aws_lb_target_group.main.*.arn)
  host-header        = var.url
}

resource "aws_service_discovery_service" "main" {
  count = var.sd_enabled ? 1 : 0

  name = var.project

  dns_config {
    namespace_id = var.namespace_id

    dns_records {
      ttl  = 10
      type = "A"
    }

    routing_policy = "MULTIVALUE"
  }

  health_check_custom_config {
    failure_threshold = 1
  }

  tags = var.common_tags

  # Remove after https://github.com/terraform-providers/terraform-provider-aws/issues/4853 is resolved
  # provisioner "local-exec" {
  #   when    = destroy
  #   command = "${path.module}/servicediscovery-drain.sh ${self.id}"
  # }
}

# ECS Service
resource "aws_ecs_service" "main" {
  name             = local.name
  cluster          = var.cluster_arn
  task_definition  = var.task_definition_arn
  launch_type      = var.launch_type
  platform_version = var.launch_type == "FARGATE" ? var.platform_version : null

  desired_count                      = var.desired_count
  deployment_minimum_healthy_percent = var.min_percent
  deployment_maximum_percent         = var.max_percent

  dynamic "load_balancer" {
    for_each = local.abl_enabled
    content {
      target_group_arn = join("", aws_lb_target_group.main.*.arn)
      container_name   = local.container_name
      container_port   = var.container_port
    }
  }

  dynamic "service_registries" {
    for_each = local.sd_enabled
    content {
      registry_arn   = join("", aws_service_discovery_service.main.*.arn)
      container_name = var.project
    }
  }

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

  enable_ecs_managed_tags = var.enable_ecs_managed_tags
  propagate_tags          = var.enable_ecs_managed_tags ? "TASK_DEFINITION" : null
  tags                    = var.common_tags

  wait_for_steady_state = var.wait_for_steady_state

  lifecycle {
    ignore_changes = [desired_count]
  }
}

resource "aws_route53_record" "www" {
  count   = var.route53_zone_id == "" ? 0 : 1
  zone_id = var.route53_zone_id
  name    = var.url
  type    = "A"

  alias {
    name                   = var.alb_dns_name
    zone_id                = var.alb_zone_id
    evaluate_target_health = var.route53_eval_health
  }
}
