import { Op } from 'sequelize';
import { getUrl } from '@blocklet/sdk';
import { PaymentMethod, PaymentCurrency } from '../store/models';
import logger from '../libs/logger';

export async function syncCurrencyLogo() {
  const where = {
    logo: {
      [Op.or]: [
        { [Op.like]: '%/methods/%.png' },
        { [Op.like]: '%/currencies/%.png' },
        { [Op.like]: '%/methods/%.svg' },
        { [Op.like]: '%/currencies/%.svg' },
      ],
    },
  };

  const [paymentMethods, paymentCurrencies] = await Promise.all([
    PaymentMethod.findAll({ where }),
    PaymentCurrency.findAll({ where }),
  ]);

  const promises: Promise<any>[] = [];

  const updateLogo = (item: PaymentMethod | PaymentCurrency) => {
    const { logo } = item;

    // 匹配 /methods/ 和 /currencies/ 路径下的 logo
    const methodsMatch = /\/methods\/(stripe|arcblock|ethereum|base)\.(png|svg)$/.test(logo);
    const currenciesMatch = /\/currencies\/[^/]+\.(png|svg)$/.test(logo);

    if (methodsMatch || currenciesMatch) {
      let newLogo: string;

      if (methodsMatch) {
        // 处理 /methods/ 路径
        newLogo = getUrl(logo.replace(/^.*?(\/methods\/.*)$/, '$1'));
      } else {
        newLogo = getUrl(logo.replace(/^.*?(\/currencies\/.*)$/, '$1'));
      }
      if (newLogo !== logo) {
        promises.push((item as any).update({ logo: newLogo }));
        logger.info(`Updating logo: ${logo} -> ${newLogo}`);
      }
    }
  };

  paymentMethods.forEach(updateLogo);
  paymentCurrencies.forEach(updateLogo);

  try {
    await Promise.all(promises);
    logger.info(`Updated ${promises.length} logo(s)`);
  } catch (error) {
    logger.error('syncCurrency error', error);
  }
}
