module "default_tags" {
  source             = "git@github.com:theorchard/terraform-default-tags.git//?ref=2.0.0"
  environment        = var.environment
  application_family = var.application_family
  service_name       = var.service_name
  team_name          = var.team_name
}

provider "aws" {
  region = var.aws_region

  default_tags {
    tags = module.default_tags.tags
  }
}

provider "aws" {
  region  = var.aws_region
  alias   = "networking"
  profile = "networking"

  default_tags {
    tags = module.default_tags.tags
  }
}

terraform {
  backend "s3" {
    bucket  = "qa-dx-terraform-state"
    key     = "qa/dx-proxy-alb/terraform.tfstate"
    region  = "eu-central-1"
    encrypt = "true"
  }
}

module "vpc_info" {
  source = "git@github.com:theorchard/terraform-vpc-info.git//?ref=3.1.0"

  environment = var.environment
}

data "aws_route53_zone" "route53_zone" {
  provider = aws.networking

  name = "${var.domain_name}."
}

data "aws_acm_certificate" "smedx_net" {
  domain   = "*.${var.domain_name}"
  statuses = ["ISSUED"]
}

data "aws_ec2_managed_prefix_list" "vpn_ny_users" {
  name = "vpn-ny-users"
}

# Security Group for ALB
resource "aws_security_group" "dx_proxy_alb_sg" {
  name        = "${var.environment}-${var.service_name}-alb-sg"
  description = "Security group for DX proxy ALB"
  vpc_id      = module.vpc_info.vpc_id

  ingress {
    description     = "HTTPS from VPC"
    from_port       = 443
    to_port         = 443
    protocol        = "tcp"
    prefix_list_ids = [data.aws_ec2_managed_prefix_list.vpn_ny_users.id]
  }

  egress {
    description = "All outbound traffic"
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name = "${var.environment}-${var.service_name}-alb-sg"
  }
}

# Application Load Balancer
resource "aws_lb" "dx_proxy_alb" {
  name               = "${var.environment}-${var.service_name}-alb"
  internal           = true
  load_balancer_type = "application"
  security_groups    = [aws_security_group.dx_proxy_alb_sg.id]
  subnets            = module.vpc_info.default_private_subnet_ids

  enable_deletion_protection = false
  enable_http2               = true
  drop_invalid_header_fields = true

  access_logs {
    bucket  = "shared-orcd-lb-logs-eu-central-1"
    prefix  = "${var.environment}-${var.service_name}-alb"
    enabled = true
  }

  tags = {
    Name = "${var.environment}-${var.service_name}-alb"
  }
}

# HTTPS Listener
resource "aws_lb_listener" "https" {
  load_balancer_arn = aws_lb.dx_proxy_alb.arn
  port              = "443"
  protocol          = "HTTPS"
  ssl_policy        = "ELBSecurityPolicy-TLS13-1-2-FIPS-PQ-2025-09"
  certificate_arn   = data.aws_acm_certificate.smedx_net.arn

  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.dx_ui.arn
  }
}

# Target Group for dx-ui (Angular frontend)
resource "aws_lb_target_group" "dx_ui" {
  #checkov:skip=CKV_AWS_378:Ensure AWS Load Balancer doesn't use HTTP protocol
  name                 = "${var.environment}-${var.service_name}-ui-target-group"
  port                 = 8080
  protocol             = "HTTP"
  vpc_id               = module.vpc_info.vpc_id
  target_type          = "ip"
  deregistration_delay = 30

  health_check {
    enabled             = true
    healthy_threshold   = 2
    unhealthy_threshold = 3
    timeout             = 5
    interval            = 30
    path                = "/health"
    protocol            = "HTTP"
    matcher             = "200-299"
  }

  tags = {
    Name = "${var.environment}-${var.service_name}-ui-target-group"
  }
}

# Target Group for dx-ui-service (Java backend)
resource "aws_lb_target_group" "dx_ui_service" {
  #checkov:skip=CKV_AWS_378:Ensure AWS Load Balancer doesn't use HTTP protocol
  name                 = "${var.environment}-${var.service_name}-ui-svc-target-group"
  port                 = 8080
  protocol             = "HTTP"
  vpc_id               = module.vpc_info.vpc_id
  target_type          = "ip"
  deregistration_delay = 30

  health_check {
    enabled             = true
    healthy_threshold   = 2
    unhealthy_threshold = 3
    timeout             = 5
    interval            = 30
    path                = "/dx-ui-service/api/v1/actuator/health"
    protocol            = "HTTP"
    matcher             = "200-299"
  }

  tags = {
    Name = "${var.environment}-${var.service_name}-ui-svc-target-group"
  }
}

# Target Group for dx-advsearch-service (Java backend)
resource "aws_lb_target_group" "dx_advsearch_service" {
  #checkov:skip=CKV_AWS_378:Ensure AWS Load Balancer doesn't use HTTP protocol
  name                 = "${var.environment}-${var.service_name}-advsrch-target-group"
  port                 = 8080
  protocol             = "HTTP"
  vpc_id               = module.vpc_info.vpc_id
  target_type          = "ip"
  deregistration_delay = 30

  health_check {
    enabled             = true
    healthy_threshold   = 2
    unhealthy_threshold = 3
    timeout             = 5
    interval            = 30
    path                = "/dx-advsearch-service/api/v1/actuator/health"
    protocol            = "HTTP"
    matcher             = "200-299"
  }

  tags = {
    Name = "${var.environment}-${var.service_name}-advsrch-target-group"
  }
}


# Listener Rule for /digital-exchange/* -> dx-ui (Angular frontend)
# Priority 100 - highest priority for UI routes
resource "aws_lb_listener_rule" "dx_ui" {
  listener_arn = aws_lb_listener.https.arn
  priority     = 100

  action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.dx_ui.arn
  }

  condition {
    path_pattern {
      values = ["/digital-exchange/*"]
    }
  }

  tags = {
    Name = "${var.environment}-${var.service_name}-ui-rule"
  }
}

# Listener Rule for /dx-ui-service/* -> dx-ui-service (Java backend)
# Priority 90
resource "aws_lb_listener_rule" "dx_ui_service" {
  listener_arn = aws_lb_listener.https.arn
  priority     = 90

  action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.dx_ui_service.arn
  }

  condition {
    path_pattern {
      values = ["/dx-ui-service/*"]
    }
  }

  tags = {
    Name = "${var.environment}-${var.service_name}-ui-svc-rule"
  }
}

# Listener Rule for /dx-advsearch-service/* -> dx-advsearch-service (Java backend)
# Priority 80
resource "aws_lb_listener_rule" "dx_advsearch_service" {
  listener_arn = aws_lb_listener.https.arn
  priority     = 80

  action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.dx_advsearch_service.arn
  }

  condition {
    path_pattern {
      values = ["/dx-advsearch-service/*"]
    }
  }

  tags = {
    Name = "${var.environment}-${var.service_name}-advsrch-rule"
  }
}

# Route53 Record
resource "aws_route53_record" "dx_proxy_alb" {
  provider = aws.networking

  zone_id = data.aws_route53_zone.route53_zone.zone_id
  name    = "${var.environment}-${var.application_family}.${var.domain_name}"
  type    = "A"

  alias {
    name                   = aws_lb.dx_proxy_alb.dns_name
    zone_id                = aws_lb.dx_proxy_alb.zone_id
    evaluate_target_health = true
  }
}

module "dx_proxy_custom_waf" {
  source            = "git@github.com:theorchard/terraform-aws-waf.git//?ref=2.0.2"
  environment       = var.environment
  service_name      = var.service_name
  aws_region        = var.aws_region
  count_waf_enabled = false
  block_waf_enabled = true
}

resource "aws_wafv2_web_acl_association" "lb_waf_association" {
  resource_arn = aws_lb.dx_proxy_alb.arn
  web_acl_arn  = module.dx_proxy_custom_waf.waf_blocking_arn_output
}
