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

    try {
      const rows = await queryInterface.sequelize.query(
        "SELECT to_regclass('public.\"tenantsOrganizationsOrganizations\"') AS regclass_name;",
        {
          transaction,
          type: Sequelize.QueryTypes.SELECT,
        },
      );
      const tableName = rows[0].regclass_name;

      if (tableName) {
        await transaction.commit();
        return;
      }

      await queryInterface.createTable(
        'tenantsOrganizationsOrganizations',
        {
          createdAt: {
            type: Sequelize.DataTypes.DATE,
            allowNull: false,
          },
          updatedAt: {
            type: Sequelize.DataTypes.DATE,
            allowNull: false,
          },
          tenants_organizationsId: {
            type: Sequelize.DataTypes.UUID,
            allowNull: false,
            primaryKey: true,
            references: {
              model: 'tenants',
              key: 'id',
            },
            onDelete: 'CASCADE',
            onUpdate: 'CASCADE',
          },
          organizationId: {
            type: Sequelize.DataTypes.UUID,
            allowNull: false,
            primaryKey: true,
            references: {
              model: 'organizations',
              key: 'id',
            },
            onDelete: 'CASCADE',
            onUpdate: 'CASCADE',
          },
        },
        { transaction },
      );

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

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

    try {
      const rows = await queryInterface.sequelize.query(
        "SELECT to_regclass('public.\"tenantsOrganizationsOrganizations\"') AS regclass_name;",
        {
          transaction,
          type: Sequelize.QueryTypes.SELECT,
        },
      );
      const tableName = rows[0].regclass_name;

      if (!tableName) {
        await transaction.commit();
        return;
      }

      await queryInterface.dropTable('tenantsOrganizationsOrganizations', { transaction });
      await transaction.commit();
    } catch (err) {
      await transaction.rollback();
      throw err;
    }
  },
};
