'use strict';

/**
 * Remove duplicate element_type_defaults rows.
 * Keeps the oldest entry (by createdAt) for each element_type.
 * This fixes the unique constraint violation during project creation.
 */
module.exports = {
  async up(queryInterface, Sequelize) {
    // Find duplicate element_types
    const duplicates = await queryInterface.sequelize.query(
      `SELECT element_type, COUNT(*) as count
       FROM element_type_defaults
       WHERE "deletedAt" IS NULL
       GROUP BY element_type
       HAVING COUNT(*) > 1`,
      { type: Sequelize.QueryTypes.SELECT },
    );

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

    console.log(
      `Found ${duplicates.length} element_types with duplicates:`,
      duplicates.map((d) => d.element_type).join(', '),
    );

    // For each duplicate element_type, keep oldest and delete others
    for (const dup of duplicates) {
      // Get all rows for this element_type, ordered by createdAt
      const rows = await queryInterface.sequelize.query(
        `SELECT id, "createdAt"
         FROM element_type_defaults
         WHERE element_type = :element_type AND "deletedAt" IS NULL
         ORDER BY "createdAt" ASC`,
        {
          replacements: { element_type: dup.element_type },
          type: Sequelize.QueryTypes.SELECT,
        },
      );

      // Keep the first (oldest), delete the rest
      const idsToDelete = rows.slice(1).map((r) => r.id);

      if (idsToDelete.length > 0) {
        await queryInterface.sequelize.query(
          `DELETE FROM element_type_defaults WHERE id IN (:ids)`,
          { replacements: { ids: idsToDelete } },
        );
        console.log(
          `Deleted ${idsToDelete.length} duplicate(s) for element_type: ${dup.element_type}`,
        );
      }
    }

    console.log('Duplicate removal complete.');
  },

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