apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: momo-postgres
  namespace: momo
spec:
  serviceName: momo-postgres
  replicas: 1
  selector:
    matchLabels:
      app: momo-postgres
  template:
    metadata:
      labels:
        app: momo-postgres
    spec:
      containers:
      - name: postgres
        image: postgres:15-alpine
        ports:
        - containerPort: 5432
        env:
        - name: POSTGRES_USER
          valueFrom:
            secretKeyRef:
              name: momo-secrets
              key: POSTGRES_USER
        - name: POSTGRES_PASSWORD
          valueFrom:
            secretKeyRef:
              name: momo-secrets
              key: POSTGRES_PASSWORD
        - name: POSTGRES_DB
          value: momo_analytics
        # 優化 PostgreSQL 配置
        - name: POSTGRES_INITDB_ARGS
          value: "--encoding=UTF8"
        # 資源配置 (增加以提升穩定性)
        resources:
          requests:
            memory: 512Mi
            cpu: 200m
          limits:
            memory: 2Gi
            cpu: 1000m
        # 健康檢查 (放寬設定以減少誤判)
        livenessProbe:
          exec:
            command:
            - pg_isready
            - -U
            - momo
            - -d
            - momo_analytics
          initialDelaySeconds: 60
          periodSeconds: 60
          timeoutSeconds: 15
          failureThreshold: 5
          successThreshold: 1
        readinessProbe:
          exec:
            command:
            - pg_isready
            - -U
            - momo
            - -d
            - momo_analytics
          initialDelaySeconds: 15
          periodSeconds: 20
          timeoutSeconds: 10
          failureThreshold: 3
          successThreshold: 1
        volumeMounts:
        - name: postgres-data
          mountPath: /var/lib/postgresql/data
  volumeClaimTemplates:
  - metadata:
      name: postgres-data
    spec:
      accessModes: ["ReadWriteOnce"]
      storageClassName: local-path
      resources:
        requests:
          storage: 10Gi
---
apiVersion: v1
kind: Service
metadata:
  name: momo-postgres
  namespace: momo
spec:
  clusterIP: None
  ports:
  - port: 5432
  selector:
    app: momo-postgres
