'use strict';

/**
 * Remove invalid element_type_defaults entries.
 * Only valid element types defined in DEFAULT_ROWS should exist.
 */
module.exports = {
  async up(queryInterface, Sequelize) {
    // Valid element types as defined in element_type_defaults.js DEFAULT_ROWS
    const validTypes = [
      'navigation_next',
      'navigation_prev',
      'tooltip',
      'description',
      'gallery',
      'carousel',
      'video_player',
      'audio_player',
      'spot',
      'logo',
      'popup',
    ];

    // Find invalid entries
    const invalidEntries = await queryInterface.sequelize.query(
      `SELECT id, element_type, name
       FROM element_type_defaults
       WHERE element_type NOT IN (:validTypes)
       AND "deletedAt" IS NULL`,
      {
        replacements: { validTypes },
        type: Sequelize.QueryTypes.SELECT,
      },
    );

    if (invalidEntries.length === 0) {
      console.log('No invalid element_type_defaults found.');
      return;
    }

    console.log(
      `Found ${invalidEntries.length} invalid element_type_defaults:`,
    );
    invalidEntries.forEach((entry) => {
      console.log(`  - ${entry.name} (${entry.element_type})`);
    });

    // Delete invalid entries
    const idsToDelete = invalidEntries.map((e) => e.id);
    await queryInterface.sequelize.query(
      `DELETE FROM element_type_defaults WHERE id IN (:ids)`,
      { replacements: { ids: idsToDelete } },
    );

    // Also delete from project_element_defaults
    const deletedProjectDefaults = await queryInterface.sequelize.query(
      `DELETE FROM project_element_defaults
       WHERE element_type NOT IN (:validTypes)
       RETURNING id, element_type`,
      {
        replacements: { validTypes },
        type: Sequelize.QueryTypes.SELECT,
      },
    );

    console.log(
      `Deleted ${idsToDelete.length} invalid element_type_defaults.`,
    );
    console.log(
      `Deleted ${deletedProjectDefaults.length} invalid project_element_defaults.`,
    );
  },

  async down(_queryInterface, _Sequelize) {
    // Cannot restore deleted invalid entries
    console.log(
      'Down migration not applicable - invalid entries cannot be restored.',
    );
  },
};
