resource "aws_lb" "catherine_fc_load_balancer" {
  name               = "catherine-fc-lb"
  internal           = false
  load_balancer_type = "application"
  security_groups    = [aws_security_group.catherine_fc_lb_sg.id]
  subnets            = var.internal_subnet_ids

  enable_deletion_protection = true

  tags = var.tags
}
resource "aws_lb_listener" "catherine_fc_load_balancer_listener" {
  load_balancer_arn = aws_lb.catherine_fc_load_balancer.arn
  port              = "443"
  protocol          = "HTTPS"
  ssl_policy        = "ELBSecurityPolicy-TLS-1-2-Ext-2018-06"
  certificate_arn   = "arn:aws:acm:ap-northeast-1:353699021357:certificate/df8e9911-1f45-4e3f-90cb-4c34f3ed3e50"

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

resource "aws_lb_listener_rule" "catherine_fc_alb_listener_admin" {
  listener_arn = aws_lb_listener.catherine_fc_load_balancer_listener.arn
  priority     = 1
  action {
    type = "authenticate-cognito"

    authenticate_cognito {
      user_pool_arn       = aws_cognito_user_pool.catherine_fc_admin_cognito_pool.arn
      user_pool_client_id = aws_cognito_user_pool_client.catherine_fc_admin_cognito_pool_client.id
      user_pool_domain    = aws_cognito_user_pool_domain.catherine_fc_admin_cognito_pool_domain.domain
      on_unauthenticated_request = "authenticate"
      session_cookie_name = "CatherineFCAdmin"
      session_timeout = 86400
    }
  }
  action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.target_group_web.arn
  }

  condition {
    path_pattern {
      values = ["/admin*"]
    }
  }
}

resource "aws_lb_listener_rule" "catherine_fc_alb_listener_admin_api" {
  listener_arn = aws_lb_listener.catherine_fc_load_balancer_listener.arn
  priority     = 2
  action {
    type = "authenticate-cognito"

    authenticate_cognito {
      user_pool_arn       = aws_cognito_user_pool.catherine_fc_admin_cognito_pool.arn
      user_pool_client_id = aws_cognito_user_pool_client.catherine_fc_admin_cognito_pool_client.id
      user_pool_domain    = aws_cognito_user_pool_domain.catherine_fc_admin_cognito_pool_domain.domain
      on_unauthenticated_request = "deny"
      session_cookie_name = "CatherineFCAdmin"
      session_timeout = 86400
    }
  }
  action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.target_group_web.arn
  }

  condition {
    path_pattern {
      values = ["/api/admin*"]
    }
  }
}
