terraform {
  required_providers {
    ovh = {
      source  = "ovh/ovh"
      version = "2.3.0"
    }
  }
}

provider "ovh" {
  endpoint      = "ovh-eu"
}

variable "local_project_id" {
  type    = string
  default = "var.simpl_project_id"
}

variable "local_region" {
  type    = string
  default = "var.simpl_region"
}

# The flavor can be selected directly, name_filter in DS does strict equality
data "ovh_cloud_project_flavors" "flavors" {
  service_name = var.local_project_id
  name_filter  = "var.simpl_flavor"
  region       = var.local_region
}

# The image must be selected from its region based list using name filtering
data "ovh_cloud_project_images" "image" {
  service_name = var.local_project_id
  region       = var.local_region
}

locals {
  selected_image = one([
    for m in data.ovh_cloud_project_images.image.images : m if m.name == "var.simpl_image"
  ])
  selected_flavor = one(data.ovh_cloud_project_flavors.flavors.flavors)
}

resource "ovh_cloud_project_instance" "simpl_vm" {
  service_name   = var.local_project_id
  region         = var.local_region
  billing_period = "hourly"

  boot_from {
    image_id = local.selected_image.id
  }

  flavor {
    flavor_id = local.selected_flavor.id
  }

  name = "offering-enterprise-server-{UUID}-terraform"

  ssh_key_create {
    name       = "default-user-key"
    public_key = "var.simpl_ssh_public_key"
  }

  network {
    public = true
  }

  user_data = "var.simpl_cloud_init"
}

output "vmIps" {
  depends_on = [ovh_cloud_project_instance.simpl_vm]
  value      = tolist(ovh_cloud_project_instance.simpl_vm.addresses[*].ip)
}
