import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * 添加咨询状态字段到conversations表
 *
 * 新增字段：
 * - consulting_stage: 当前咨询阶段
 * - consulting_state: 完整的咨询状态JSON
 * - collected_info: 已收集的用户信息
 * - recommended_programs: 推荐的移民方案
 * - conversion_path: 转化路径
 * - device_info: 用户设备信息
 */
export class AddConsultingStateToConversation1706100000000 implements MigrationInterface {
  name = 'AddConsultingStateToConversation1706100000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    // 添加咨询阶段字段
    await queryRunner.query(`
      ALTER TABLE "conversations"
      ADD COLUMN IF NOT EXISTS "consulting_stage" VARCHAR(30) DEFAULT 'greeting'
    `);

    // 添加咨询状态JSON字段
    await queryRunner.query(`
      ALTER TABLE "conversations"
      ADD COLUMN IF NOT EXISTS "consulting_state" JSONB
    `);

    // 添加已收集信息字段
    await queryRunner.query(`
      ALTER TABLE "conversations"
      ADD COLUMN IF NOT EXISTS "collected_info" JSONB
    `);

    // 添加推荐方案字段
    await queryRunner.query(`
      ALTER TABLE "conversations"
      ADD COLUMN IF NOT EXISTS "recommended_programs" TEXT[]
    `);

    // 添加转化路径字段
    await queryRunner.query(`
      ALTER TABLE "conversations"
      ADD COLUMN IF NOT EXISTS "conversion_path" VARCHAR(30)
    `);

    // 添加设备信息字段
    await queryRunner.query(`
      ALTER TABLE "conversations"
      ADD COLUMN IF NOT EXISTS "device_info" JSONB
    `);

    // 创建索引：按咨询阶段查询
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS "idx_conversations_consulting_stage"
      ON "conversations" ("consulting_stage")
    `);

    // 创建索引：按转化路径查询
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS "idx_conversations_conversion_path"
      ON "conversations" ("conversion_path")
    `);

    // 创建GIN索引：按收集的信息查询（JSONB）
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS "idx_conversations_collected_info"
      ON "conversations" USING GIN ("collected_info")
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // 删除索引
    await queryRunner.query(`DROP INDEX IF EXISTS "idx_conversations_collected_info"`);
    await queryRunner.query(`DROP INDEX IF EXISTS "idx_conversations_conversion_path"`);
    await queryRunner.query(`DROP INDEX IF EXISTS "idx_conversations_consulting_stage"`);

    // 删除字段
    await queryRunner.query(`ALTER TABLE "conversations" DROP COLUMN IF EXISTS "device_info"`);
    await queryRunner.query(`ALTER TABLE "conversations" DROP COLUMN IF EXISTS "conversion_path"`);
    await queryRunner.query(`ALTER TABLE "conversations" DROP COLUMN IF EXISTS "recommended_programs"`);
    await queryRunner.query(`ALTER TABLE "conversations" DROP COLUMN IF EXISTS "collected_info"`);
    await queryRunner.query(`ALTER TABLE "conversations" DROP COLUMN IF EXISTS "consulting_state"`);
    await queryRunner.query(`ALTER TABLE "conversations" DROP COLUMN IF EXISTS "consulting_stage"`);
  }
}
