apiVersion: batch/v1
kind: Job
metadata:
  name: db-schema-init
  namespace: ddb
  labels:
    app: postgresql-init
    layer: data
spec:
  backoffLimit: 3
  ttlSecondsAfterFinished: 3600  # Keep Job for 1 hour after completion
  template:
    metadata:
      labels:
        app: postgresql-init
    spec:
      serviceAccountName: default
      restartPolicy: Never
      containers:
      - name: schema-init
        image: postgres:16.2-alpine
        env:
        - name: PGHOST
          value: ddb-cluster-rw.ddb.svc.cluster.local
        - name: PGPORT
          value: "5432"
        - name: PGDATABASE
          value: app
        - name: PGUSER
          value: app
        - name: PGPASSWORD
          valueFrom:
            secretKeyRef:
              name: ddb-cluster-app
              key: password
        command:
        - /bin/sh
        - -c
        - |
          # Wait for cluster to be ready
          echo "Waiting for PostgreSQL to be ready..."
          until pg_isready -h $PGHOST -p $PGPORT -U $PGUSER; do
            echo "Waiting..."
            sleep 5
          done

          echo "Creating schemas..."

          # Create schemas from ConfigMap
          psql -h $PGHOST -p $PGPORT -U $PGUSER -d $PGDATABASE << 'EOF'
          CREATE SCHEMA IF NOT EXISTS authentik;
          GRANT USAGE ON SCHEMA authentik TO app;
          GRANT CREATE ON SCHEMA authentik TO app;

          CREATE SCHEMA IF NOT EXISTS temporal;
          GRANT USAGE ON SCHEMA temporal TO app;
          GRANT CREATE ON SCHEMA temporal TO app;

          CREATE SCHEMA IF NOT EXISTS vault;
          GRANT USAGE ON SCHEMA vault TO app;
          GRANT CREATE ON SCHEMA vault TO app;

          GRANT USAGE ON SCHEMA public TO app;
          GRANT CREATE ON SCHEMA public TO app;
          EOF

          echo "✓ Schema initialization complete"
