apiVersion: batch/v1
kind: Job
metadata:
  name: migrate-knowledge-entries
  namespace: awoooi-prod
  labels:
    app: awoooi-migration
    phase: "kb-1"
spec:
  ttlSecondsAfterFinished: 300
  backoffLimit: 1
  template:
    spec:
      restartPolicy: Never
      containers:
      - name: migrate
        image: postgres:15-alpine
        command:
        - /bin/sh
        - -c
        - |
          echo "=========================================="
          echo "Knowledge Base Phase 1 - CREATE TABLE"
          echo "=========================================="

          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'

          -- 建立 Enum types (IF NOT EXISTS)
          -- Create enum types if not exist (safe for re-run)
          DO 'BEGIN CREATE TYPE entrytype AS ENUM (''incident_case'', ''runbook'', ''best_practice'', ''postmortem''); EXCEPTION WHEN duplicate_object THEN NULL; END';
          DO 'BEGIN CREATE TYPE entrysource AS ENUM (''ai_extracted'', ''human''); EXCEPTION WHEN duplicate_object THEN NULL; END';
          DO 'BEGIN CREATE TYPE entrystatus AS ENUM (''draft'', ''review'', ''approved'', ''archived''); EXCEPTION WHEN duplicate_object THEN NULL; END';

          -- 建立 knowledge_entries table
          CREATE TABLE IF NOT EXISTS knowledge_entries (
              id              VARCHAR(36) PRIMARY KEY,
              title           VARCHAR(255) NOT NULL,
              content         TEXT NOT NULL,
              entry_type      entrytype NOT NULL,
              category        VARCHAR(100) NOT NULL,
              tags            JSONB DEFAULT '[]'::jsonb NOT NULL,
              source          entrysource NOT NULL,
              status          entrystatus NOT NULL DEFAULT 'draft',
              related_incident_id VARCHAR(30),
              related_playbook_id VARCHAR(255),
              view_count      INTEGER NOT NULL DEFAULT 0,
              created_by      VARCHAR(100),
              created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
              updated_at      TIMESTAMPTZ NOT NULL DEFAULT NOW()
          );

          -- 建立 Indexes
          CREATE INDEX IF NOT EXISTS ix_knowledge_entry_type ON knowledge_entries(entry_type);
          CREATE INDEX IF NOT EXISTS ix_knowledge_category ON knowledge_entries(category);
          CREATE INDEX IF NOT EXISTS ix_knowledge_status ON knowledge_entries(status);
          CREATE INDEX IF NOT EXISTS ix_knowledge_created_at ON knowledge_entries(created_at);

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

          EOSQL

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