import { DataTypes, QueryTypes } from 'sequelize';
import { Migration, safeApplyColumnChanges } from '../migrate';

export const up: Migration = async ({ context }) => {
  try {
    // 添加 success_subscription_count 字段
    await safeApplyColumnChanges(context, {
      checkout_sessions: [
        {
          name: 'success_subscription_count',
          field: {
            type: DataTypes.INTEGER,
            defaultValue: 0,
          },
        },
      ],
    });

    const sessions = (await context.sequelize.query(
      `SELECT id, subscription_id, subscription_groups 
     FROM checkout_sessions 
     WHERE payment_status = 'paid' AND (mode = 'subscription' OR mode = 'setup')`,
      { type: QueryTypes.SELECT }
    )) as any[];

    if (sessions.length > 0) {
      // 收集更新数据
      const updates: { id: string; count: number }[] = [];
      for (const session of sessions) {
        let count = 0;
        if (session.subscription_groups) {
          try {
            const groups = JSON.parse(session.subscription_groups);
            count = Object.keys(groups).length;
          } catch (e) {
            console.warn(`Failed to parse subscription_groups for session ${session.id}`);
          }
        }

        if (count === 0 && session.subscription_id) {
          count = 1;
        }

        if (count > 0) {
          updates.push({ id: session.id, count });
        }
      }

      // 使用事务确保原子性
      await context.sequelize.transaction(async (t) => {
        for (const update of updates) {
          // eslint-disable-next-line no-await-in-loop
          await context.sequelize.query('UPDATE checkout_sessions SET success_subscription_count = ? WHERE id = ?', {
            replacements: [update.count, update.id],
            transaction: t,
            type: QueryTypes.UPDATE,
          });
        }
      });
    }
  } catch (error) {
    console.error('Migration failed:', error);
    throw error;
  }
};

export const down: Migration = async ({ context }) => {
  await context.removeColumn('checkout_sessions', 'success_subscription_count');
};
