---
# Secret - database password shared with the XorMon deployment
apiVersion: v1
kind: Secret
metadata:
  name: db-secret
  namespace: xormon
type: Opaque
stringData:
  password: "CHANGE_ME"   # use the same password in xormon.yaml / xormon-secret

---
# ServiceAccount required to assign anyuid SCC in OpenShift
# After applying run:
#   oc adm policy add-scc-to-user anyuid -z timescaledb -n xormon
apiVersion: v1
kind: ServiceAccount
metadata:
  name: timescaledb
  namespace: xormon

---
# StatefulSet for TimescaleDB (timescale/timescaledb from Docker Hub)
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: timescaledb
  namespace: xormon
  labels:
    app: timescaledb
spec:
  serviceName: timescaledb
  replicas: 1
  selector:
    matchLabels:
      app: timescaledb
  template:
    metadata:
      labels:
        app: timescaledb
    spec:
      serviceAccountName: timescaledb
      containers:
        - name: timescaledb
          image: timescale/timescaledb:latest-pg16   # pin to a specific tag in production, e.g. 2.19.0-pg16
          imagePullPolicy: IfNotPresent
          # Increased background workers for TimescaleDB jobs (continuous aggregates, compression...)
          # Default of 8 is insufficient; adjust based on the number of databases and policies
          args:
            - "-cmax_worker_processes=32"
            - "-ctimescaledb.max_background_workers=16"
          ports:
            - containerPort: 5432
              protocol: TCP
          env:
            - name: POSTGRES_DB
              value: "xormon"
            - name: POSTGRES_USER
              value: "postgres"
            - name: POSTGRES_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: db-secret
                  key: password
            # Subdirectory prevents "directory not empty" error on first start
            - name: PGDATA
              value: "/var/lib/postgresql/data/pgdata"
          volumeMounts:
            - name: db-data
              mountPath: /var/lib/postgresql/data
          resources:
            requests:
              cpu: "1"
              memory: "2Gi"
            limits:
              cpu: "4"
              memory: "8Gi"
      # fsGroup 70 = postgres group in Alpine-based timescaledb image
      securityContext:
        fsGroup: 70
  volumeClaimTemplates:
    - metadata:
        name: db-data
      spec:
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 100Gi
        # storageClassName: standard   # adjust for your cluster

---
# Internal ClusterIP service - reachable as "timescaledb:5432" within the namespace
apiVersion: v1
kind: Service
metadata:
  name: timescaledb
  namespace: xormon
spec:
  type: ClusterIP
  selector:
    app: timescaledb
  ports:
    - port: 5432
      targetPort: 5432
      protocol: TCP
