terraform {
  required_providers {
    random = {
      source  = "hashicorp/random"
      version = "~> 3.6"
    }
    rabbitmq = {
      source  = "cyrilgdn/rabbitmq"
      version = "~> 1.8"
    }
  }
}

# Generate random password for the tenant user
resource "random_password" "tenant_password" {
  length           = 32
  special          = false
  min_upper        = 2
  min_lower        = 2
  min_numeric      = 2
}

# Create SSH tunnel to RabbitMQ Management API on VPS
module "ssh_tunnel" {
  source  = "flaupretre/tunnel/ssh"
  version = "2.2.1"

  target_host = "127.0.0.1"
  target_port = var.target_port

  gateway_host = var.server_ip
  gateway_user = var.ssh_user
  
  # Tunnel will be created when needed
  timeout = "30s"
}

# Configure RabbitMQ provider to use the SSH tunnel
provider "rabbitmq" {
  endpoint = "http://${module.ssh_tunnel.host}:${module.ssh_tunnel.port}"
  username = var.admin_username
  password = var.admin_password
}

# Create the virtual host
resource "rabbitmq_vhost" "tenant_vhost" {
  depends_on = [var.wait_on]
  
  name = var.tenant_name
}

# Create the user
resource "rabbitmq_user" "tenant_user" {
  depends_on = [var.wait_on]
  
  name     = var.tenant_name
  password = random_password.tenant_password.result
  tags     = []
}

# Grant permissions to the user on the vhost
resource "rabbitmq_permissions" "tenant_permissions" {
  user  = rabbitmq_user.tenant_user.name
  vhost = rabbitmq_vhost.tenant_vhost.name

  permissions {
    configure = ".*"
    write     = ".*"
    read      = ".*"
  }
}