apiVersion: batch/v1
kind: Job
metadata:
  name: migrate-phase18-audit-logs
  namespace: awoooi-prod
  labels:
    app: awoooi-migration
    phase: "18"
spec:
  ttlSecondsAfterFinished: 300  # 5 分鐘後自動清理
  backoffLimit: 1
  template:
    spec:
      restartPolicy: Never
      containers:
      - name: migrate
        image: postgres:15-alpine
        command:
        - /bin/sh
        - -c
        - |
          echo "=========================================="
          echo "Phase 18 AuditLog Migration"
          echo "=========================================="

          # 從 SECRET 讀取連線資訊
          DB_HOST=$(echo $DATABASE_URL | sed 's/.*@\([^:]*\):.*/\1/')
          DB_PORT=$(echo $DATABASE_URL | sed 's/.*:\([0-9]*\)\/.*/\1/')
          DB_NAME=$(echo $DATABASE_URL | sed 's/.*\/\([^?]*\).*/\1/')
          DB_USER=$(echo $DATABASE_URL | sed 's/.*\/\/\([^:]*\):.*/\1/')
          DB_PASS=$(echo $DATABASE_URL | sed 's/.*:\/\/[^:]*:\([^@]*\)@.*/\1/')

          echo "Connecting to: $DB_HOST:$DB_PORT/$DB_NAME"

          export PGPASSWORD="$DB_PASS"

          # 執行遷移
          psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" <<'EOSQL'
          -- 1. authorization_channel
          DO $$
          BEGIN
              IF NOT EXISTS (
                  SELECT 1 FROM information_schema.columns
                  WHERE table_name = 'audit_logs' AND column_name = 'authorization_channel'
              ) THEN
                  ALTER TABLE audit_logs ADD COLUMN authorization_channel VARCHAR(20);
                  RAISE NOTICE 'Added: authorization_channel';
              ELSE
                  RAISE NOTICE 'Exists: authorization_channel';
              END IF;
          END $$;

          -- 2. retry_count
          DO $$
          BEGIN
              IF NOT EXISTS (
                  SELECT 1 FROM information_schema.columns
                  WHERE table_name = 'audit_logs' AND column_name = 'retry_count'
              ) THEN
                  ALTER TABLE audit_logs ADD COLUMN retry_count INTEGER DEFAULT 0 NOT NULL;
                  RAISE NOTICE 'Added: retry_count';
              ELSE
                  RAISE NOTICE 'Exists: retry_count';
              END IF;
          END $$;

          -- 3. failure_classification
          DO $$
          BEGIN
              IF NOT EXISTS (
                  SELECT 1 FROM information_schema.columns
                  WHERE table_name = 'audit_logs' AND column_name = 'failure_classification'
              ) THEN
                  ALTER TABLE audit_logs ADD COLUMN failure_classification VARCHAR(50);
                  RAISE NOTICE 'Added: failure_classification';
              ELSE
                  RAISE NOTICE 'Exists: failure_classification';
              END IF;
          END $$;

          -- 4. source_approval_id
          DO $$
          BEGIN
              IF NOT EXISTS (
                  SELECT 1 FROM information_schema.columns
                  WHERE table_name = 'audit_logs' AND column_name = 'source_approval_id'
              ) THEN
                  ALTER TABLE audit_logs ADD COLUMN source_approval_id VARCHAR(36);
                  RAISE NOTICE 'Added: source_approval_id';
              ELSE
                  RAISE NOTICE 'Exists: source_approval_id';
              END IF;
          END $$;

          -- 5. auto_repair_attempted
          DO $$
          BEGIN
              IF NOT EXISTS (
                  SELECT 1 FROM information_schema.columns
                  WHERE table_name = 'audit_logs' AND column_name = 'auto_repair_attempted'
              ) THEN
                  ALTER TABLE audit_logs ADD COLUMN auto_repair_attempted BOOLEAN DEFAULT FALSE NOT NULL;
                  RAISE NOTICE 'Added: auto_repair_attempted';
              ELSE
                  RAISE NOTICE 'Exists: auto_repair_attempted';
              END IF;
          END $$;

          -- 6. auto_repair_result
          DO $$
          BEGIN
              IF NOT EXISTS (
                  SELECT 1 FROM information_schema.columns
                  WHERE table_name = 'audit_logs' AND column_name = 'auto_repair_result'
              ) THEN
                  ALTER TABLE audit_logs ADD COLUMN auto_repair_result TEXT;
                  RAISE NOTICE 'Added: auto_repair_result';
              ELSE
                  RAISE NOTICE 'Exists: auto_repair_result';
              END IF;
          END $$;

          -- 創建索引
          CREATE INDEX IF NOT EXISTS ix_audit_authorization_channel ON audit_logs(authorization_channel);
          CREATE INDEX IF NOT EXISTS ix_audit_failure_classification ON audit_logs(failure_classification);
          CREATE INDEX IF NOT EXISTS ix_audit_source_approval_id ON audit_logs(source_approval_id);

          -- 驗證
          SELECT column_name, data_type
          FROM information_schema.columns
          WHERE table_name = 'audit_logs'
          ORDER BY ordinal_position;
          EOSQL

          echo "=========================================="
          echo "Migration completed!"
          echo "=========================================="
        envFrom:
        - secretRef:
            name: awoooi-secrets
        resources:
          requests:
            memory: "64Mi"
            cpu: "100m"
          limits:
            memory: "128Mi"
            cpu: "200m"
