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

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

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

      await queryInterface.createTable(
        'ui_elements',
        {
          id: {
            type: Sequelize.DataTypes.UUID,
            defaultValue: Sequelize.DataTypes.UUIDV4,
            primaryKey: true,
          },
          element_type: {
            type: Sequelize.DataTypes.TEXT,
            allowNull: false,
          },
          name: {
            type: Sequelize.DataTypes.TEXT,
            allowNull: true,
          },
          settings_json: {
            type: Sequelize.DataTypes.TEXT,
            allowNull: true,
          },
          sort_order: {
            type: Sequelize.DataTypes.INTEGER,
            allowNull: false,
            defaultValue: 0,
          },
          createdById: {
            type: Sequelize.DataTypes.UUID,
            allowNull: true,
            references: {
              model: 'users',
              key: 'id',
            },
          },
          updatedById: {
            type: Sequelize.DataTypes.UUID,
            allowNull: true,
            references: {
              model: 'users',
              key: 'id',
            },
          },
          createdAt: { type: Sequelize.DataTypes.DATE },
          updatedAt: { type: Sequelize.DataTypes.DATE },
          deletedAt: { type: Sequelize.DataTypes.DATE },
          importHash: {
            type: Sequelize.DataTypes.STRING(255),
            allowNull: true,
            unique: true,
          },
        },
        { transaction },
      );

      await queryInterface.addIndex('ui_elements', ['element_type'], { transaction });
      await queryInterface.addIndex('ui_elements', ['sort_order'], { transaction });
      await queryInterface.addIndex('ui_elements', ['deletedAt'], { 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.ui_elements') AS regclass_name;",
        {
          transaction,
          type: Sequelize.QueryTypes.SELECT,
        },
      );

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

      await queryInterface.dropTable('ui_elements', { transaction });

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