'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    const transaction = await queryInterface.sequelize.transaction();

    try {
      const table = await queryInterface.describeTable('users');

      if (!table.emailOtpHash) {
        await queryInterface.addColumn(
          'users',
          'emailOtpHash',
          {
            type: Sequelize.DataTypes.TEXT,
            allowNull: true,
          },
          { transaction },
        );
      }

      if (!table.emailOtpExpiresAt) {
        await queryInterface.addColumn(
          'users',
          'emailOtpExpiresAt',
          {
            type: Sequelize.DataTypes.DATE,
            allowNull: true,
          },
          { transaction },
        );
      }

      if (!table.emailOtpLastSentAt) {
        await queryInterface.addColumn(
          'users',
          'emailOtpLastSentAt',
          {
            type: Sequelize.DataTypes.DATE,
            allowNull: true,
          },
          { transaction },
        );
      }

      if (!table.emailOtpAttempts) {
        await queryInterface.addColumn(
          'users',
          'emailOtpAttempts',
          {
            type: Sequelize.DataTypes.INTEGER,
            allowNull: false,
            defaultValue: 0,
          },
          { transaction },
        );
      }

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

  async down(queryInterface) {
    const transaction = await queryInterface.sequelize.transaction();

    try {
      const table = await queryInterface.describeTable('users');

      if (table.emailOtpAttempts) {
        await queryInterface.removeColumn('users', 'emailOtpAttempts', { transaction });
      }

      if (table.emailOtpLastSentAt) {
        await queryInterface.removeColumn('users', 'emailOtpLastSentAt', { transaction });
      }

      if (table.emailOtpExpiresAt) {
        await queryInterface.removeColumn('users', 'emailOtpExpiresAt', { transaction });
      }

      if (table.emailOtpHash) {
        await queryInterface.removeColumn('users', 'emailOtpHash', { transaction });
      }

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