resource "aws_cloudwatch_log_group" "dsms-auth-stage" {
  #checkov:skip=CKV_AWS_338: Ensure CloudWatch log groups retains logs for at least 1 year
  name              = "/ecs/dsms-auth-stage"
  retention_in_days = 7
}

resource "aws_ecs_task_definition" "dsms-auth-stage" {
  family                   = "${lower(var.vpc_name)}-dsms-auth-stage-td"
  network_mode             = "awsvpc"
  requires_compatibilities = ["FARGATE"]
  cpu                      = "512"
  memory                   = "2048"
  execution_role_arn       = "arn:aws:iam::718729873097:role/ecsTaskExecutionRole"
  task_role_arn            = "arn:aws:iam::718729873097:role/dsms-task-role"

  container_definitions = jsonencode([
    {
      name      = "dsms-auth"
      image     = "718729873097.dkr.ecr.eu-central-1.amazonaws.com/dsms/auth:3.8.1"
      essential = true

      portMappings = [{
        containerPort = 9100
        hostPort      = 9100
        protocol      = "tcp"
      }]

      healthCheck = {
        command     = ["CMD-SHELL", "curl -f http://localhost:9100/actuator/health || exit 1"]
        interval    = 30
        timeout     = 5
        retries     = 3
        startPeriod = 60
      }

      environment = [
        { name = "SPRING_PROFILES_ACTIVE", value = "stage" },
        { name = "JAVA_TOOL_OPTIONS", value = "-XX:+UseContainerSupport" }
      ]

      secrets = [
      {
        name      = "DB_PASSWORD"
        valueFrom = "arn:aws:secretsmanager:eu-central-1:718729873097:secret:dsms-stage/config-m5yqgi:DB_PASSWORD::"
      },
      {
        name      = "EUREKA_PASSWORD"
        valueFrom = "arn:aws:secretsmanager:eu-central-1:718729873097:secret:dsms-stage/config-m5yqgi:EUREKA_PASSWORD::"
      }
      ]

      logConfiguration = {
        logDriver = "awslogs"
        options = {
          awslogs-region        = var.region
          awslogs-group         = "/ecs/dsms-auth-stage"
          awslogs-stream-prefix = "ecs"
        }
      }
    }
  ])
}


resource "aws_ecs_service" "dsms-auth-stage" {
  name                  = "${lower(var.vpc_name)}-dsms-auth-stage"
  cluster               = "arn:aws:ecs:eu-central-1:718729873097:cluster/dsms-cluster"
  task_definition       = aws_ecs_task_definition.dsms-auth-stage.arn
  desired_count         = 2 
  launch_type           = "FARGATE"
  platform_version      = "LATEST"
  enable_execute_command = true
  deployment_minimum_healthy_percent = 100
  deployment_maximum_percent         = 200

  network_configuration {
    subnets         = [aws_subnet.DIGSYS-S3-IAPP-1A.id, aws_subnet.DIGSYS-S3-IAPP-1B.id]
    security_groups = [aws_security_group.DIGSYS-S3-DSMS-AUTH-SG.id]
    assign_public_ip = false
  }

}


resource "aws_cloudwatch_metric_alarm" "dsms_auth_stage_running_count_low" {
  alarm_name          = "${lower(var.vpc_name)}-dsms-auth-stage-running-count-low"
  alarm_description   = "Triggers when RunningTaskCount for dsms-auth-stage is less than 2"
  namespace           = "ECS/ContainerInsights"
  metric_name         = "RunningTaskCount"
  dimensions = {
    ClusterName = "dsms-cluster"
    ServiceName = aws_ecs_service.dsms-auth-stage.name
  }
  statistic           = "Minimum"
  period              = 60
  evaluation_periods  = 1
  threshold           = 2
  comparison_operator = "LessThanThreshold"
  treat_missing_data  = "missing"
  alarm_actions = [aws_sns_topic.dsms_stage_alerts.arn]
  ok_actions    = [aws_sns_topic.dsms_stage_alerts.arn]
}
