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

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

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

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

      if (!tableDefinition.type) {
        await queryInterface.addColumn(
          'assets',
          'type',
          {
            type: Sequelize.DataTypes.ENUM,
            values: [
              'icon',
              'background_image',
              'audio',
              'video',
              'transition',
              'logo',
              'favicon',
              'document',
              'general',
            ],
            allowNull: false,
            defaultValue: 'general',
          },
          { transaction },
        );

        await queryInterface.sequelize.query(
          `
            UPDATE assets
            SET type = (
              CASE
                WHEN name ILIKE '[ICON] %' OR name ILIKE '[IMAGE] %' THEN 'icon'
                WHEN name ILIKE '[BACKGROUND] %' THEN 'background_image'
                WHEN name ILIKE '[AUDIO] %' THEN 'audio'
                WHEN name ILIKE '[VIDEO] %' THEN 'video'
                WHEN name ILIKE '[TRANSITION] %' THEN 'transition'
                WHEN name ILIKE '[LOGO] %' THEN 'logo'
                WHEN asset_type = 'audio' THEN 'audio'
                WHEN asset_type = 'video' THEN 'video'
                ELSE 'general'
              END
            )::"enum_assets_type"
            WHERE type = 'general';
          `,
          { transaction },
        );

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

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

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

      if (tableDefinition.type) {
        await queryInterface.removeIndex('assets', ['type'], { transaction });
        await queryInterface.removeColumn('assets', 'type', { transaction });
      }

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