const crypto = require('crypto');

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,
        },
      );

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

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

  async down(queryInterface) {
    const transaction = await queryInterface.sequelize.transaction();
    try {
      await queryInterface.bulkDelete(
        'currencies',
        { code: 'ZAR', importHash: 'qweli-default-zar' },
        { transaction },
      );
      await transaction.commit();
    } catch (err) {
      await transaction.rollback();
      throw err;
    }
  },
};
