resource "aws_secretsmanager_secret" "pmapi_auth" {
  name  = "${local.environment_name}-AuthSecret"
  tags  = { Environment = local.environment_name }
}

resource "aws_secretsmanager_secret" "pmapi_db_conn_string" {
  name  = "${local.environment_name}-DbConnString"
  tags  = { Environment = local.environment_name }
}

resource "aws_ecs_task_definition" "pmapi" {
  family                    = local.environment_name
  network_mode              = "bridge"
  requires_compatibilities  = ["EC2"]
  execution_role_arn        = aws_iam_role.ecs_task.arn

  # See https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ContainerDefinition.html
  container_definitions = jsonencode([
    {
      name              = local.environment_name
      image             = "${var.ecr_repo.repository_url}:${data.external.git_describe.result.version}"
      cpu               = 128
      memory            = 128
      memoryReservation = 32
      environment       = [
        {
          name  = "PORT"
          value = "80"
        }
      ]
      portMappings      = [
        {
          protocol      = "tcp"
          containerPort = 80
        }
      ]
      secrets           = [
        {
          name        = "AUTH_SECRET"
          description = "Auth secret used to hash and salt passwords."
          valueFrom   = aws_secretsmanager_secret.pmapi_auth.arn
        },
        {
          name      = "DB_CONN_STRING"
          description = "Connection string with user credentials."
          valueFrom = aws_secretsmanager_secret.pmapi_db_conn_string.arn
        }
      ]
    }
  ])

  tags = {
    Name        = local.api_domain_name
    Environment = local.environment_name
  }
}

resource "aws_ecs_service" "pmapi" {
  name            = local.environment_name
  cluster         = data.terraform_remote_state.jdbsoft.outputs.aws_ecs_cluster_ortis.id
  task_definition = aws_ecs_task_definition.pmapi.arn
  desired_count   = 1
  launch_type     = "EC2"

  load_balancer {
    target_group_arn  = aws_lb_target_group.pmapi.arn
    container_name    = local.environment_name
    container_port    = 80
  }

  tags = {
    Name        = local.api_domain_name
    Environment = local.environment_name
  }
}