apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: postgres
  labels:
    app.kubernetes.io/name: postgres
spec:
  serviceName: postgres
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: postgres
  template:
    metadata:
      labels:
        app.kubernetes.io/name: postgres
    spec:
      containers:
        - name: postgres
          image: postgres:16-alpine
          # Legacy installations store PostgreSQL directly at the PVC root.
          # Fresh ext4 volumes may contain lost+found, so initialize new clusters
          # in a child directory without hiding an existing root-level cluster.
          command:
            - sh
            - -ec
            - |
              if [ -f /var/lib/postgresql/data/PG_VERSION ]; then
                export PGDATA=/var/lib/postgresql/data
              else
                export PGDATA=/var/lib/postgresql/data/pgdata
              fi
              exec docker-entrypoint.sh postgres
          ports:
            - containerPort: 5432
              name: postgres
          env:
            - name: POSTGRES_DB
              value: skillhub
            - name: POSTGRES_USER
              valueFrom:
                secretKeyRef:
                  name: skillhub-secret
                  key: spring-datasource-username
            - name: POSTGRES_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: skillhub-secret
                  key: spring-datasource-password
          volumeMounts:
            - name: postgres-data
              mountPath: /var/lib/postgresql/data
          readinessProbe:
            exec:
              command:
                - pg_isready
                - -U
                - skillhub
            initialDelaySeconds: 10
            periodSeconds: 10
          livenessProbe:
            exec:
              command:
                - pg_isready
                - -U
                - skillhub
            initialDelaySeconds: 30
            periodSeconds: 15
          resources:
            requests:
              cpu: 100m
              memory: 256Mi
            limits:
              cpu: 500m
              memory: 512Mi
  volumeClaimTemplates:
    - metadata:
        name: postgres-data
      spec:
        accessModes:
          - ReadWriteOnce
        resources:
          requests:
            storage: 10Gi
---
apiVersion: v1
kind: Service
metadata:
  name: postgres
  labels:
    app.kubernetes.io/name: postgres
spec:
  type: ClusterIP
  ports:
    - port: 5432
      targetPort: postgres
      name: postgres
  selector:
    app.kubernetes.io/name: postgres
