/**
 * Migration: move-pay-config-fields
 * Version: 25.3.0
 * Generated: 2026-01-14T11:11:23.982Z
 *
 * This migration was automatically generated by TypeORM
 * based on entity definition changes.
 * Also includes: add-order-source (添加订单来源字段)
 */

import { PayConfigPayType } from "@buildingai/constants/shared/payconfig.constant";
import { MigrationInterface, QueryRunner } from "typeorm";

export class Migration1768389082132 implements MigrationInterface {
    name = "Migration1768389082132";

    public async up(queryRunner: QueryRunner): Promise<void> {
        // 添加新的 config 列（如果不存在）
        await queryRunner.query(`ALTER TABLE "payconfig" ADD COLUMN IF NOT EXISTS "config" jsonb`);
        await queryRunner.query(`COMMENT ON COLUMN "payconfig"."config" IS '具体支付方式的配置'`);

        // 检查哪些字段存在
        const tableColumns = await queryRunner.query(`
            SELECT column_name
            FROM information_schema.columns
            WHERE table_schema = 'public' AND table_name = 'payconfig'
        `);
        const columnNames = tableColumns.map((col: any) => col.column_name);

        // 迁移数据：将旧字段的数据迁移到 config 字段
        if (
            columnNames.includes("app_id") ||
            columnNames.includes("mch_id") ||
            columnNames.includes("api_key") ||
            columnNames.includes("pay_sign_key") ||
            columnNames.includes("cert") ||
            columnNames.includes("merchant_type") ||
            columnNames.includes("pay_version") ||
            columnNames.includes("pay_auth_dir")
        ) {
            // 构建动态 SELECT 查询，只包含存在的字段
            const selectFields = ["id", "pay_type"];
            const optionalFields = [
                "app_id",
                "merchant_type",
                "pay_version",
                "mch_id",
                "api_key",
                "pay_sign_key",
                "cert",
                "pay_auth_dir",
                "config",
            ];

            for (const field of optionalFields) {
                if (columnNames.includes(field)) {
                    selectFields.push(field);
                }
            }

            // 查询所有记录
            const configs = await queryRunner.query(`
                SELECT ${selectFields.join(", ")}
                FROM payconfig
            `);

            // 更新每条记录
            for (const row of configs) {
                let config: any = {};

                // 解析现有 config（如果有）
                if (row.config) {
                    try {
                        config =
                            typeof row.config === "string" ? JSON.parse(row.config) : row.config;
                    } catch {
                        // 忽略解析错误，使用空配置
                    }
                }

                const payTypeNum =
                    typeof row.pay_type === "string" ? parseInt(row.pay_type) : row.pay_type;
                if (payTypeNum === PayConfigPayType.WECHAT) {
                    const wechatConfig: any = {
                        ...(config || {}),
                    };

                    // 安全地访问可能不存在的字段并迁移到 config
                    if (columnNames.includes("app_id") && row.app_id) {
                        wechatConfig.appId = row.app_id;
                    }
                    if (columnNames.includes("mch_id") && row.mch_id) {
                        wechatConfig.mchId = row.mch_id;
                    }
                    if (columnNames.includes("api_key") && row.api_key) {
                        wechatConfig.apiKey = row.api_key;
                    }
                    if (columnNames.includes("pay_sign_key") && row.pay_sign_key) {
                        wechatConfig.paySignKey = row.pay_sign_key;
                    }
                    if (columnNames.includes("cert") && row.cert) {
                        wechatConfig.cert = row.cert;
                    }
                    if (columnNames.includes("merchant_type") && row.merchant_type) {
                        wechatConfig.merchantType = row.merchant_type;
                    }
                    if (columnNames.includes("pay_version") && row.pay_version) {
                        wechatConfig.payVersion = row.pay_version;
                    }
                    if (columnNames.includes("pay_auth_dir") && row.pay_auth_dir) {
                        wechatConfig.payAuthDir = row.pay_auth_dir;
                    }

                    config = wechatConfig;
                }

                // 更新数据库
                await queryRunner.query(`UPDATE payconfig SET config = $1 WHERE id = $2`, [
                    JSON.stringify(config),
                    row.id,
                ]);
            }
        }

        // 安全删除旧字段
        await queryRunner.query(`ALTER TABLE "payconfig" DROP COLUMN IF EXISTS "pay_version"`);
        await queryRunner.query(`ALTER TABLE "payconfig" DROP COLUMN IF EXISTS "merchant_type"`);
        await queryRunner.query(`ALTER TABLE "payconfig" DROP COLUMN IF EXISTS "mch_id"`);
        await queryRunner.query(`ALTER TABLE "payconfig" DROP COLUMN IF EXISTS "api_key"`);
        await queryRunner.query(`ALTER TABLE "payconfig" DROP COLUMN IF EXISTS "pay_sign_key"`);
        await queryRunner.query(`ALTER TABLE "payconfig" DROP COLUMN IF EXISTS "cert"`);
        await queryRunner.query(`ALTER TABLE "payconfig" DROP COLUMN IF EXISTS "pay_auth_dir"`);
        await queryRunner.query(`ALTER TABLE "payconfig" DROP COLUMN IF EXISTS "app_id"`);

        // 安全删除类型（如果存在）
        await queryRunner.query(
            `DO $$ BEGIN
                DROP TYPE IF EXISTS "public"."payconfig_pay_version_enum";
            EXCEPTION
                WHEN undefined_object THEN NULL;
            END $$;`,
        );
        await queryRunner.query(
            `DO $$ BEGIN
                DROP TYPE IF EXISTS "public"."payconfig_merchant_type_enum";
            EXCEPTION
                WHEN undefined_object THEN NULL;
            END $$;`,
        );

        // 添加订单来源字段到 membership_order 表
        await queryRunner.query(`
            ALTER TABLE "membership_order" 
            ADD COLUMN IF NOT EXISTS "source" integer DEFAULT 1
        `);
        await queryRunner.query(`
            COMMENT ON COLUMN "membership_order"."source" IS '订单来源: 0-系统调整, 1-订单购买'
        `);

        // 将现有订单的 source 设置为 1（订单购买）
        await queryRunner.query(`
            UPDATE "membership_order" 
            SET "source" = 1 
            WHERE "source" IS NULL
        `);
    }

    public async down(queryRunner: QueryRunner): Promise<void> {
        // 恢复旧字段
        await queryRunner.query(
            `ALTER TABLE "payconfig" ADD COLUMN IF NOT EXISTS "app_id" character varying`,
        );
        await queryRunner.query(
            `ALTER TABLE "payconfig" ADD COLUMN IF NOT EXISTS "pay_auth_dir" character varying`,
        );
        await queryRunner.query(
            `ALTER TABLE "payconfig" ADD COLUMN IF NOT EXISTS "cert" character varying`,
        );
        await queryRunner.query(
            `ALTER TABLE "payconfig" ADD COLUMN IF NOT EXISTS "pay_sign_key" character varying`,
        );
        await queryRunner.query(
            `ALTER TABLE "payconfig" ADD COLUMN IF NOT EXISTS "api_key" character varying`,
        );
        await queryRunner.query(
            `ALTER TABLE "payconfig" ADD COLUMN IF NOT EXISTS "mch_id" character varying`,
        );

        // 创建类型（如果不存在）
        await queryRunner.query(
            `DO $$ BEGIN
                CREATE TYPE "public"."payconfig_merchant_type_enum" AS ENUM('ordinary', 'child');
            EXCEPTION
                WHEN duplicate_object THEN NULL;
            END $$;`,
        );
        await queryRunner.query(
            `ALTER TABLE "payconfig" ADD COLUMN IF NOT EXISTS "merchant_type" "public"."payconfig_merchant_type_enum"`,
        );

        await queryRunner.query(
            `DO $$ BEGIN
                CREATE TYPE "public"."payconfig_pay_version_enum" AS ENUM('V2', 'V3');
            EXCEPTION
                WHEN duplicate_object THEN NULL;
            END $$;`,
        );
        await queryRunner.query(
            `ALTER TABLE "payconfig" ADD COLUMN IF NOT EXISTS "pay_version" "public"."payconfig_pay_version_enum"`,
        );

        // 从 config 恢复数据
        const configs = await queryRunner.query(`SELECT id, pay_type, config FROM payconfig`);

        for (const row of configs) {
            if (!row.config) continue;

            let config: any = {};
            try {
                config = typeof row.config === "string" ? JSON.parse(row.config) : row.config;
            } catch {
                continue;
            }

            const payTypeNum =
                typeof row.pay_type === "string" ? parseInt(row.pay_type) : row.pay_type;
            if (payTypeNum === PayConfigPayType.WECHAT) {
                // 提取字段
                const appId = config.appId || null;
                const merchantType = config.merchantType || null;
                const payVersion = config.payVersion || null;
                const mchId = config.mchId || null;
                const apiKey = config.apiKey || null;
                const paySignKey = config.paySignKey || null;
                const cert = config.cert || null;
                const payAuthDir = config.payAuthDir || null;

                // 更新基础字段
                await queryRunner.query(
                    `
                    UPDATE payconfig
                        SET app_id = $1, merchant_type = $2, pay_version = $3,
                            mch_id = $4, api_key = $5, pay_sign_key = $6,
                            cert = $7, pay_auth_dir = $8
                        WHERE id = $9
                    `,
                    [
                        appId,
                        merchantType,
                        payVersion,
                        mchId,
                        apiKey,
                        paySignKey,
                        cert,
                        payAuthDir,
                        row.id,
                    ],
                );
            }
        }

        // 删除 config 列
        await queryRunner.query(`ALTER TABLE "payconfig" DROP COLUMN IF EXISTS "config"`);

        // 删除订单来源字段
        await queryRunner.query(`
            ALTER TABLE "membership_order" 
            DROP COLUMN IF EXISTS "source"
        `);
    }
}
