locals {
  name    = "${var.env_prefix}-${var.project_group}-${var.project}"
  tg_name = length(local.name) > 32 ? "${var.env_prefix}-${var.project_group}-${random_string.tg_id.result}" : local.name
}

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

# Target group for ECS service
resource "aws_lb_target_group" "main" {
  name                 = local.tg_name
  port                 = var.tg_port
  protocol             = var.protocol
  vpc_id               = var.vpc_id
  deregistration_delay = var.tg_deregistration_delay
  target_type          = "ip"

  health_check {
    port     = "traffic-port"
    protocol = var.protocol
  }

  tags = var.common_tags
}

module "internal_nlb_listener" {
  source                = "../../../ec2/nlb/listener"
  nlb_arn               = var.nlb_arn
  nlb_listener_protocol = var.protocol
  nlb_listener_port     = var.tg_port
  default_tg_arn        = aws_lb_target_group.main.arn
}
/*
resource "aws_lb_listener_rule" "main"{
  listener_arn = module.internal_nlb_listener.nlb_listener.arn
  action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.main.arn
  }
  condition {
    source_ip {
      values = ["0.0.0.0/0"]
    }
  }
}
*/
# ECS Service
resource "aws_ecs_service" "main" {
  name             = local.name
  cluster          = var.cluster_arn
  task_definition  = var.task_definition_arn
  launch_type      = "FARGATE"
  platform_version = "1.4.0"
  desired_count    = var.task_count

  load_balancer {
    target_group_arn = aws_lb_target_group.main.arn
    container_name   = var.project
    container_port   = var.container_port
  }

  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" "entrypoint" {
  count   = var.route53_zone_id == "" ? 0 : 1
  zone_id = var.route53_zone_id
  name    = var.fqdn
  type    = "A"

  alias {
    name                   = var.nlb_dns_name
    zone_id                = var.nlb_zone_id
    evaluate_target_health = var.route53_eval_health
  }
}
