resource "kubernetes_service_account" "openwebui" {

  metadata {
    name      = "openwebui-sa"
    namespace = kubernetes_namespace.openwebui.metadata[0].name
  }

  automount_service_account_token = false
}

resource "kubernetes_deployment" "openwebui" {
  metadata {
    name      = "openwebui"
    namespace = kubernetes_namespace.openwebui.metadata[0].name
    labels = {
      app = "openwebui"
    }
  }

  spec {
    replicas = 1

    selector {
      match_labels = {
        app = "openwebui"
      }
    }

    strategy {
      type = "RollingUpdate"
    }

    template {
      metadata {
        labels = {
          app = "openwebui"
        }
      }

      spec {
        service_account_name            = kubernetes_service_account.openwebui.metadata[0].name
        automount_service_account_token = false

        container {
          name  = "app"
          image = "ghcr.io/open-webui/open-webui:${var.tag}"

          security_context {
            allow_privilege_escalation = false
          }

          port {
            name           = "http"
            container_port = 8080
          }

          readiness_probe {
            tcp_socket {
              port = 8080
            }
            initial_delay_seconds = 5
            period_seconds        = 10
            failure_threshold     = 10
          }

          volume_mount {
            name       = "openwebui-data"
            mount_path = "/app/backend/data"
          }
        }

        volume {
          name = "openwebui-data"
          host_path {
            path = local.openwebui_data
          }
        }
      }
    }
  }
}

resource "kubernetes_service" "openwebui" {
  metadata {
    name      = "http"
    namespace = kubernetes_namespace.openwebui.metadata[0].name
  }

  spec {
    selector = {
      app = "openwebui"
    }

    port {
      name        = "http"
      port        = 8080
      target_port = 8080
    }

    type       = "ClusterIP"
    cluster_ip = "None"
  }

  lifecycle {
    ignore_changes = [
      metadata[0].annotations
    ]
  }
}
