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             = "HTTP"
  vpc_id               = var.vpc_id
  deregistration_delay = var.tg_deregistration_delay
  target_type          = "ip"

  health_check {
    path                = var.tg_health_check_path
    port                = "traffic-port"
    protocol            = "HTTP"
    matcher             = var.tg_health_check_matcher
    timeout             = var.tg_health_check_timeout
    healthy_threshold   = var.tg_health_check_healthy_threshold
    interval            = var.tg_health_check_interval
    unhealthy_threshold = var.tg_health_check_unhealthy_threshold
  }

  tags = var.common_tags
}

# ALB rules for
module "alb_rules" {
  source             = "../../../ec2/alb/https_rule_with_redirect"
  https_listener_arn = var.https_listener_arn
  tg_arn             = aws_lb_target_group.main.arn
  host-header        = var.url
}

# 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" "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
  }
}
