#!/bin/bash
# Test Migration 020: Unified Prompt System (Issue #28)

echo "═══════════════════════════════════════════════════════════"
echo "Migration 020: Unified Prompt System - Verification Tests"
echo "═══════════════════════════════════════════════════════════"
echo ""

POSTGRES_CONTAINER="dev-mitai-postgres"
DB_USER="mitai_dev"
DB_NAME="mitai_dev"

echo "Test 1: Migration 020 applied"
echo "─────────────────────────────────────────────────────────"
docker exec $POSTGRES_CONTAINER psql -U $DB_USER -d $DB_NAME -c \
  "SELECT version, applied_at FROM schema_migrations WHERE version = '020';"
echo ""

echo "Test 2: New columns exist in ai_prompts"
echo "─────────────────────────────────────────────────────────"
docker exec $POSTGRES_CONTAINER psql -U $DB_USER -d $DB_NAME -c \
  "SELECT column_name, data_type
   FROM information_schema.columns
   WHERE table_name = 'ai_prompts'
   AND column_name IN ('type', 'stages', 'output_format', 'output_schema')
   ORDER BY column_name;"
echo ""

echo "Test 3: Existing prompts migrated to pipeline type"
echo "─────────────────────────────────────────────────────────"
docker exec $POSTGRES_CONTAINER psql -U $DB_USER -d $DB_NAME -c \
  "SELECT slug, type,
   CASE WHEN stages IS NOT NULL THEN 'Has stages' ELSE 'No stages' END as stages_status,
   output_format
   FROM ai_prompts
   WHERE slug LIKE 'pipeline_%'
   LIMIT 5;"
echo ""

echo "Test 4: Pipeline configs migrated to ai_prompts"
echo "─────────────────────────────────────────────────────────"
docker exec $POSTGRES_CONTAINER psql -U $DB_USER -d $DB_NAME -c \
  "SELECT slug, name, type,
   jsonb_array_length(stages) as num_stages
   FROM ai_prompts
   WHERE slug LIKE 'pipeline_config_%';"
echo ""

echo "Test 5: Stages JSONB structure (sample)"
echo "─────────────────────────────────────────────────────────"
docker exec $POSTGRES_CONTAINER psql -U $DB_USER -d $DB_NAME -c \
  "SELECT slug, jsonb_pretty(stages) as stages_structure
   FROM ai_prompts
   WHERE slug LIKE 'pipeline_config_%'
   LIMIT 1;"
echo ""

echo "Test 6: Backup table created"
echo "─────────────────────────────────────────────────────────"
docker exec $POSTGRES_CONTAINER psql -U $DB_USER -d $DB_NAME -c \
  "SELECT COUNT(*) as backup_count FROM pipeline_configs_backup_pre_020;"
echo ""

echo "Test 7: Indices created"
echo "─────────────────────────────────────────────────────────"
docker exec $POSTGRES_CONTAINER psql -U $DB_USER -d $DB_NAME -c \
  "SELECT indexname FROM pg_indexes
   WHERE tablename = 'ai_prompts'
   AND indexname LIKE 'idx_ai_prompts_%';"
echo ""

echo "═══════════════════════════════════════════════════════════"
echo "Migration 020 Tests Complete!"
echo "═══════════════════════════════════════════════════════════"
