data "aws_instances" "dot_net_api" {
  instance_tags = {
    role = "Apollo .NET API"
  }

  instance_state_names = ["running"]
}

module "tg_win_ws_external" {
  source = "../../../modules/ec2/tg"

  name_prefix = local.name_prefix
  common_tags = local.common_tags

  tg_name    = "win-ws-external"
  tg_vpc_id  = data.aws_vpc.main.id
  tg_targets = data.aws_instances.dot_net_api.ids

  tg_health_check_path                = "/loadBalancerStatus.aspx"
  tg_health_check_healthy_threshold   = 2
  tg_health_check_unhealthy_threshold = 5
  tg_health_check_timeout             = 15
}

module "tg_win_ws_internal" {
  source = "../../../modules/ec2/tg"

  name_prefix = local.name_prefix
  common_tags = local.common_tags

  tg_name    = "win-ws-internal"
  tg_vpc_id  = data.aws_vpc.main.id
  tg_targets = data.aws_instances.dot_net_api.ids

  tg_health_check_path                = "/loadBalancerStatus.aspx"
  tg_health_check_healthy_threshold   = 2
  tg_health_check_unhealthy_threshold = 5
  tg_health_check_timeout             = 15
}

resource "aws_alb_listener_rule" "win_ws_internal" {
  listener_arn = data.aws_lb_listener.internal_https_listener.arn

  action {
    type             = "forward"
    target_group_arn = module.tg_win_ws_internal.tg.arn
  }

  condition {
    host_header {
      values = [module.domains[local.env_prefix]["admin-api"]]
    }
  }
}

resource "aws_alb_listener_rule" "win_ws_external" {
  listener_arn = data.aws_lb_listener.external_https_listener.arn

  action {
    type             = "forward"
    target_group_arn = module.tg_win_ws_external.tg.arn
  }

  condition {
    host_header {
      values = [module.domains[local.env_prefix]["filtr-api"]]
    }
  }
}

resource "aws_route53_record" "adminapi_filtr_com_record" {
  zone_id = data.aws_route53_zone.filtr_com_zone.zone_id
  name    = module.domains[local.env_prefix]["admin-api"]
  type    = "A"

  alias {
    name                   = data.aws_lb.internal_alb.dns_name
    zone_id                = data.aws_lb.internal_alb.zone_id
    evaluate_target_health = false
  }

  provider = aws.gdb-delphi-dev
}

resource "aws_route53_record" "api_filtr_com_record" {
  zone_id = data.aws_route53_zone.filtr_com_zone.zone_id
  name    = module.domains[local.env_prefix]["filtr-api"]
  type    = "A"

  alias {
    name                   = data.aws_lb.external_alb.dns_name
    zone_id                = data.aws_lb.external_alb.zone_id
    evaluate_target_health = false
  }

  provider = aws.gdb-delphi-dev
}
