module "alb-public" {
  source  = "terraform-aws-modules/alb/aws"
  version = "~> 9.10.0"

  name    = "${var.client_name}-${var.stage}-alb-public"
  vpc_id  = var.vpc_id
  subnets = slice(var.public_subnets, 0, 2)

  internal                   = false
  enable_deletion_protection = true
  preserve_host_header       = true
  idle_timeout               = 180
  create_security_group      = false
  security_groups            = [var.alb_public_sg_id]

  listeners = {
    http = {
      port     = 80
      protocol = "HTTP"
      redirect = {
        port        = "443"
        protocol    = "HTTPS"
        status_code = "HTTP_301"
      }
    }
    https = {
      port                        = 443
      protocol                    = "HTTPS"
      ssl_policy                  = "ELBSecurityPolicy-TLS13-1-2-2021-06"
      certificate_arn             = module.acm-alb.ssl_cert_arn
      additional_certificate_arns = [data.aws_acm_certificate.waterwheel.arn]
      action_type                 = "fixed-response"
      fixed_response = {
        content_type = "text/plain"
        message_body = "default response"
        status_code  = "200"
      }

      rules = {
        waterwheel = {
          priority = 10
          actions = [
            {
              type             = "forward"
              target_group_arn = module.ec2.target_group_arns["water-wheel-supabase-server"]
            }
          ]
          conditions = [
            {
              host_header = {
                values = [
                  "waterwheel.datafy.co.za",
                  "*.waterwheel.datafy.co.za",
                ]
              }
            }
          ]
        }

        supabase = {
          priority = 20
          actions = [
            {
              type             = "forward"
              target_group_arn = module.ec2.target_group_arns["datafy-prod-supabase-server"]
            }
          ]
          conditions = [
            {
              host_header = {
                values = ["supabase.datafy.co.za"]
              }
            }
          ]
        }

        qwen = {
          priority = 30
          actions = [
            {
              type             = "forward"
              target_group_arn = module.ec2.target_group_arns["qwen3-supabase-server"]
            }
          ]
          conditions = [
            {
              host_header = {
                values = ["qwen.datafy.co.za"]
              }
            }
          ]
        }
      }
    }
  }

  access_logs = {
    bucket  = var.access_logs_bucket
    prefix  = "alb"
    enabled = true
  }

  connection_logs = {
    bucket  = var.access_logs_bucket
    prefix  = "alb"
    enabled = true
  }
}
