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

    try {
      const tableDefinitions = [
        {
          tableName: 'tenantsPropertiesProperties',
          sourceKey: 'tenants_propertiesId',
          sourceTable: 'tenants',
          targetKey: 'propertyId',
          targetTable: 'properties',
        },
        {
          tableName: 'tenantsAudit_logsAudit_logs',
          sourceKey: 'tenants_audit_logsId',
          sourceTable: 'tenants',
          targetKey: 'auditLogId',
          targetTable: 'audit_logs',
        },
      ];

      for (const definition of tableDefinitions) {
        const rows = await queryInterface.sequelize.query(
          `SELECT to_regclass('public."${definition.tableName}"') AS regclass_name;`,
          {
            transaction,
            type: Sequelize.QueryTypes.SELECT,
          },
        );
        const tableName = rows[0].regclass_name;

        if (tableName) {
          continue;
        }

        await queryInterface.createTable(
          definition.tableName,
          {
            createdAt: {
              type: Sequelize.DataTypes.DATE,
              allowNull: false,
            },
            updatedAt: {
              type: Sequelize.DataTypes.DATE,
              allowNull: false,
            },
            [definition.sourceKey]: {
              type: Sequelize.DataTypes.UUID,
              allowNull: false,
              primaryKey: true,
              references: {
                model: definition.sourceTable,
                key: 'id',
              },
              onDelete: 'CASCADE',
              onUpdate: 'CASCADE',
            },
            [definition.targetKey]: {
              type: Sequelize.DataTypes.UUID,
              allowNull: false,
              primaryKey: true,
              references: {
                model: definition.targetTable,
                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 tableNames = [
        'tenantsPropertiesProperties',
        'tenantsAudit_logsAudit_logs',
      ];

      for (const tableName of tableNames) {
        const rows = await queryInterface.sequelize.query(
          `SELECT to_regclass('public."${tableName}"') AS regclass_name;`,
          {
            transaction,
            type: Sequelize.QueryTypes.SELECT,
          },
        );
        const existingTableName = rows[0].regclass_name;

        if (!existingTableName) {
          continue;
        }

        await queryInterface.dropTable(tableName, { transaction });
      }

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