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

export const up: Migration = async ({ context }) => {
  try {
    // 查找 submit_type 为 donate 的 payment_links 记录
    const donateLinks = await context.sequelize.query(
      "SELECT line_items FROM payment_links WHERE submit_type = 'donate'",
      { type: QueryTypes.SELECT }
    );

    // 提取所有 price_id
    const priceIds = (donateLinks as any[]).flatMap((link: any) => {
      const lineItems = JSON.parse(link.line_items || '[]') || [];
      return lineItems.map((item: any) => item.price_id);
    });

    const uniquePriceIds = Array.from(new Set(priceIds));

    // 查询 prices 表并直接联接 products 表，过滤出符合条件的 product_id
    const priceRecords = await context.sequelize.query(
      `
      SELECT p.id AS price_id, p.product_id
      FROM prices p
      JOIN products pr ON pr.id = p.product_id
      WHERE p.id IN (:priceIds) AND pr.created_via != :createdVia
      `,
      {
        type: QueryTypes.SELECT,
        replacements: { priceIds: uniquePriceIds, createdVia: 'donation' },
      }
    );

    if (!priceRecords || priceRecords.length === 0) {
      // eslint-disable-next-line no-console
      console.info('No price records found or no products to update, migration completed with no changes.');
      return;
    }

    // 提取 uniqueProductIds
    const uniqueProductIds = Array.from(new Set(priceRecords.map((record: any) => record.product_id)));

    // 更新 products 表的 created_via 字段
    await context.sequelize.query("UPDATE products SET created_via = 'donation' WHERE id IN (:productIds)", {
      replacements: { productIds: uniqueProductIds },
    });

    // eslint-disable-next-line no-console
    console.info('update donation products success:', uniqueProductIds);
  } catch (error) {
    console.error('update donation products failed:', error);
    throw error;
  }
};

export const down: Migration = async () => {};
