---
# n8n Secret
apiVersion: v1
kind: Secret
metadata:
  name: n8n-secret
  namespace: tools
type: Opaque
stringData:
  N8N_BASIC_AUTH_USER: "admin"
  N8N_BASIC_AUTH_PASSWORD: "Wooo_N8n_2026"
  # 使用從現有資料提取的加密金鑰
  N8N_ENCRYPTION_KEY: "kZtCTdBNohlpqQYqjv/Magxn21X6Lsog"

---
# n8n PersistentVolumeClaim
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: n8n-data
  namespace: tools
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 5Gi
  storageClassName: local-path

---
# n8n Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
  name: n8n
  namespace: tools
  labels:
    app: n8n
spec:
  replicas: 1
  selector:
    matchLabels:
      app: n8n
  template:
    metadata:
      labels:
        app: n8n
    spec:
      containers:
        - name: n8n
          image: n8nio/n8n:latest
          ports:
            - containerPort: 5678
          env:
            - name: N8N_BASIC_AUTH_ACTIVE
              value: "true"
            - name: N8N_BASIC_AUTH_USER
              valueFrom:
                secretKeyRef:
                  name: n8n-secret
                  key: N8N_BASIC_AUTH_USER
            - name: N8N_BASIC_AUTH_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: n8n-secret
                  key: N8N_BASIC_AUTH_PASSWORD
            - name: N8N_ENCRYPTION_KEY
              valueFrom:
                secretKeyRef:
                  name: n8n-secret
                  key: N8N_ENCRYPTION_KEY
            - name: N8N_RUNNERS_DISABLED
              value: "true"
            - name: GENERIC_TIMEZONE
              value: "Asia/Taipei"
            - name: TZ
              value: "Asia/Taipei"
            - name: N8N_SECURE_COOKIE
              value: "false"
            # 明確設定 N8N_PORT 避免被 K8s Service 環境變數覆蓋
            - name: N8N_PORT
              value: "5678"
          volumeMounts:
            - name: n8n-data
              mountPath: /home/node/.n8n
          resources:
            requests:
              memory: "256Mi"
              cpu: "100m"
            limits:
              memory: "2Gi"
              cpu: "1000m"
          livenessProbe:
            httpGet:
              path: /healthz
              port: 5678
            initialDelaySeconds: 60
            periodSeconds: 30
            timeoutSeconds: 10
          readinessProbe:
            httpGet:
              path: /healthz
              port: 5678
            initialDelaySeconds: 30
            periodSeconds: 10
            timeoutSeconds: 5
      volumes:
        - name: n8n-data
          persistentVolumeClaim:
            claimName: n8n-data

---
# n8n Service
apiVersion: v1
kind: Service
metadata:
  name: n8n
  namespace: tools
spec:
  selector:
    app: n8n
  ports:
    - port: 5678
      targetPort: 5678
  type: ClusterIP
