apiVersion: batch/v1
kind: CronJob
metadata:
  name: demo-session-cleanup
  namespace: bakery-ia
  labels:
    app: demo-cleanup
    component: maintenance
spec:
  schedule: "0 * * * *"  # Every hour
  timeZone: "Europe/Madrid"
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 3
  concurrencyPolicy: Forbid
  jobTemplate:
    metadata:
      labels:
        app: demo-cleanup
    spec:
      template:
        metadata:
          labels:
            app: demo-cleanup
        spec:
          initContainers:
          - name: wait-for-migrations
            image: postgres:17-alpine
            command: ["sh", "-c",
              "echo 'Waiting for database to be ready...' && \
               until pg_isready -h demo-session-db-service -p 5432; do sleep 2; done && \
               echo 'Database ready, checking for demo_sessions table...' && \
               MAX_ATTEMPTS=60 && \
               ATTEMPT=1 && \
               until psql -h demo-session-db-service -U demo_session_user -d demo_session_db -c 'SELECT 1 FROM demo_sessions LIMIT 1;' 2>/dev/null; do \
                 if [ $ATTEMPT -ge $MAX_ATTEMPTS ]; then \
                   echo 'ERROR: demo_sessions table not created after maximum attempts'; \
                   exit 1; \
                 fi; \
                 echo \"Waiting for demo_sessions table to be created by migrations... (attempt $ATTEMPT/$MAX_ATTEMPTS)\"; \
                 ATTEMPT=$((ATTEMPT + 1)); \
                 sleep 5; \
               done && \
               echo 'demo_sessions table is ready!'"]
            env:
            - name: PGPASSWORD
              valueFrom:
                secretKeyRef:
                  name: database-secrets
                  key: DEMO_SESSION_DB_PASSWORD
            resources:
              requests:
                memory: "64Mi"
                cpu: "50m"
              limits:
                memory: "128Mi"
                cpu: "100m"
          containers:
          - name: cleanup-trigger
            image: curlimages/curl:latest
            command:
            - sh
            - -c
            - |
              echo "Triggering demo session cleanup..."
              response=$(curl -s -w "\n%{http_code}" -X POST http://demo-session-service:8000/api/v1/demo/operations/cleanup)
              http_code=$(echo "$response" | tail -n 1)
              body=$(echo "$response" | sed '$d')
              echo "Response: $body"
              echo "HTTP Status: $http_code"
              if [ "$http_code" -ge 200 ] && [ "$http_code" -lt 300 ]; then
                echo "Cleanup job enqueued successfully"
                exit 0
              else
                echo "Failed to enqueue cleanup job"
                exit 1
              fi
            resources:
              requests:
                memory: "32Mi"
                cpu: "10m"
              limits:
                memory: "64Mi"
                cpu: "50m"
          restartPolicy: OnFailure
          activeDeadlineSeconds: 30
