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

    try {
      const tableRows = await queryInterface.sequelize.query(
        "SELECT to_regclass('public.publish_events') AS regclass_name;",
        {
          transaction,
          type: Sequelize.QueryTypes.SELECT,
        },
      );

      if (!tableRows[0]?.regclass_name) {
        await transaction.commit();
        return;
      }

      const tableDefinition = await queryInterface.describeTable('publish_events', { transaction });

      if (!tableDefinition.title) {
        await queryInterface.addColumn(
          'publish_events',
          'title',
          {
            type: Sequelize.DataTypes.STRING,
            allowNull: true,
          },
          { transaction },
        );
      }

      if (!tableDefinition.description) {
        await queryInterface.addColumn(
          'publish_events',
          'description',
          {
            type: Sequelize.DataTypes.TEXT,
            allowNull: true,
          },
          { transaction },
        );
      }

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

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

    try {
      const tableRows = await queryInterface.sequelize.query(
        "SELECT to_regclass('public.publish_events') AS regclass_name;",
        {
          transaction,
          type: Sequelize.QueryTypes.SELECT,
        },
      );

      if (!tableRows[0]?.regclass_name) {
        await transaction.commit();
        return;
      }

      const tableDefinition = await queryInterface.describeTable('publish_events', { transaction });

      if (tableDefinition.description) {
        await queryInterface.removeColumn('publish_events', 'description', { transaction });
      }

      if (tableDefinition.title) {
        await queryInterface.removeColumn('publish_events', 'title', { transaction });
      }

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