apiVersion: apps/v1
kind: Deployment
metadata:
  name: medusa-deploy
spec:
  replicas: 1
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 0
      maxSurge: 1
  selector:
    matchLabels:
      app: medusa
  template:
    metadata:
      labels:
        app: medusa
    spec:
      imagePullSecrets:
        - name: gitea-registry-secret

      affinity:
        podAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            - labelSelector:
                matchLabels:
                  app: commerce-postgres
              topologyKey: kubernetes.io/hostname

      initContainers:
        - name: wait-for-postgres
          image: postgres:17-alpine
          imagePullPolicy: IfNotPresent
          command:
            - sh
            - -c
            - |
              until pg_isready -h postgres-svc -p 5432 -U "$POSTGRES_USER" -d "$POSTGRES_DB" -t 5; do
                echo "postgres no disponible aun, reintentando..."
                sleep 2
              done
          envFrom:
            - secretRef:
                name: commerce-secrets
          resources:
            requests:
              cpu: 25m
              memory: 32Mi
            limits:
              cpu: 100m
              memory: 64Mi

        - name: migrations
          image: gitea.cruzcloud.net/devops/ecommerce-medusa:v1.0.92
          imagePullPolicy: IfNotPresent
          command:
            - npx
            - medusa
            - db:migrate
          envFrom:
            - configMapRef:
                name: commerce-config
            - secretRef:
                name: commerce-secrets
          resources:
            requests:
              cpu: 50m
              memory: 256Mi
            limits:
              cpu: 500m
              memory: 768Mi

      containers:
        - name: medusa
          image: gitea.cruzcloud.net/devops/ecommerce-medusa:v1.0.92
          imagePullPolicy: IfNotPresent
          envFrom:
            - configMapRef:
                name: commerce-config
            - secretRef:
                name: commerce-secrets
          ports:
            - name: http
              containerPort: 9000
          readinessProbe:
            httpGet:
              path: /health
              port: http
            initialDelaySeconds: 20
            periodSeconds: 10
            timeoutSeconds: 5
            failureThreshold: 18
          livenessProbe:
            httpGet:
              path: /health
              port: http
            initialDelaySeconds: 60
            periodSeconds: 20
            timeoutSeconds: 5
            failureThreshold: 6
          resources:
            requests:
              cpu: 150m
              memory: 384Mi
            limits:
              cpu: 750m
              memory: 1Gi
---
apiVersion: v1
kind: Service
metadata:
  name: medusa-svc
spec:
  selector:
    app: medusa
  ports:
    - name: http
      port: 9000
      targetPort: 9000
