# ─── Postgres data volume ─────────────────────────────────────────────────────
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: rebours-postgres-data
  namespace: rebours
spec:
  accessModes: [ReadWriteOnce]
  storageClassName: local-path
  resources:
    requests:
      storage: 5Gi
---
# ─── Postgres headless service (stable DNS inside the cluster) ────────────────
apiVersion: v1
kind: Service
metadata:
  name: rebours-postgres
  namespace: rebours
spec:
  selector:
    app: rebours-postgres
  ports:
    - name: postgres
      port: 5432
      targetPort: 5432
  clusterIP: None
---
# ─── Postgres StatefulSet ─────────────────────────────────────────────────────
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: rebours-postgres
  namespace: rebours
spec:
  serviceName: rebours-postgres
  replicas: 1
  selector:
    matchLabels:
      app: rebours-postgres
  template:
    metadata:
      labels:
        app: rebours-postgres
    spec:
      containers:
        - name: postgres
          image: postgres:16-alpine
          ports:
            - containerPort: 5432
          env:
            - name: POSTGRES_DB
              valueFrom:
                secretKeyRef:
                  name: rebours-db-secret
                  key: POSTGRES_DB
            - name: POSTGRES_USER
              valueFrom:
                secretKeyRef:
                  name: rebours-db-secret
                  key: POSTGRES_USER
            - name: POSTGRES_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: rebours-db-secret
                  key: POSTGRES_PASSWORD
            - name: PGDATA
              value: /var/lib/postgresql/data/pgdata
          volumeMounts:
            - name: data
              mountPath: /var/lib/postgresql/data
          resources:
            requests:
              memory: "256Mi"
              cpu: "100m"
            limits:
              memory: "1Gi"
              cpu: "1000m"
          readinessProbe:
            exec:
              command: ["sh", "-c", "pg_isready -U $POSTGRES_USER -d $POSTGRES_DB"]
            initialDelaySeconds: 5
            periodSeconds: 10
          livenessProbe:
            exec:
              command: ["sh", "-c", "pg_isready -U $POSTGRES_USER -d $POSTGRES_DB"]
            initialDelaySeconds: 30
            periodSeconds: 30
      volumes:
        - name: data
          persistentVolumeClaim:
            claimName: rebours-postgres-data
