const crypto = require('crypto');

const CURRENCY_TABLES = [
  'contacts',
  'quotes',
  'invoices',
  'bills',
  'expenses',
  'bank_accounts',
  'bank_transactions',
  'payments',
];

module.exports = {
  async up(queryInterface) {
    const transaction = await queryInterface.sequelize.transaction();
    try {
      const now = new Date();
      const [existingRows] = await queryInterface.sequelize.query(
        'SELECT id FROM currencies WHERE code = :code AND "deletedAt" IS NULL LIMIT 1',
        {
          replacements: { code: 'ZAR' },
          transaction,
        },
      );

      let zarCurrencyId = existingRows[0]?.id;

      if (!zarCurrencyId) {
        zarCurrencyId = crypto.randomUUID();
        await queryInterface.bulkInsert(
          'currencies',
          [
            {
              id: zarCurrencyId,
              code: 'ZAR',
              name: 'South African Rand',
              symbol: 'R',
              minor_unit: 2,
              importHash: 'qweli-default-zar-backfill',
              createdAt: now,
              updatedAt: now,
            },
          ],
          { transaction },
        );
      }

      for (const tableName of CURRENCY_TABLES) {
        await queryInterface.bulkUpdate(
          tableName,
          {
            currencyId: zarCurrencyId,
            updatedAt: now,
          },
          { deletedAt: null },
          { transaction },
        );
      }

      await transaction.commit();
    } catch (err) {
      await transaction.rollback();
      throw err;
    }
  },

  async down() {
    // Intentionally no-op: previous currency choices cannot be reconstructed safely.
  },
};
