resource "helm_release" "traefik" {
  depends_on = [var.wait_on]
  name          = "traefik"
  repository    = "https://helm.traefik.io/traefik"
  chart         = "traefik"
  namespace     = var.namespace
  version       = var.chart_version
  wait          = false
  wait_for_jobs = true

  values = [
    file("${path.module}/traefik-values.yaml")
  ]
}

resource "kubernetes_manifest" "preserve-host-middleware" {
  depends_on = [helm_release.traefik]
  manifest = {
    apiVersion = "traefik.io/v1alpha1"
    kind       = "Middleware"
    metadata = {
      name      = "preserve-host-headers"
      namespace = "default"   # NOTE: Hardcoded by design
    }
    spec = {
      headers = {
        customRequestHeaders = {
          "X-Forwarded-Proto" = "https"
          "X-Forwarded-Port"  = "443"
        }
      }
    }
  }
}

resource "kubernetes_manifest" "https-redirect-middleware" {
  depends_on = [helm_release.traefik]
  manifest = {
    apiVersion = "traefik.io/v1alpha1"
    kind       = "Middleware"
    metadata = {
      name      = "redirect-to-https"
      namespace = "default"   # NOTE: Hardcoded by design
    }
    spec = {
      redirectScheme = {
        permanent = true
        scheme    = "https"
      }
    }
  }
}


output "installed" {
  value = true
  depends_on = [helm_release.traefik, kubernetes_manifest.preserve-host-middleware, kubernetes_manifest.https-redirect-middleware]
}
