'use strict';

/**
 * Migration: Rename ui_elements table to element_type_defaults
 *
 * This migration renames the table for better clarity:
 * - ui_elements contained GLOBAL platform-wide default settings
 * - The new name element_type_defaults better describes this purpose
 * - Adds index on deletedAt for soft delete queries
 */
module.exports = {
  async up(queryInterface, Sequelize) {
    // Check if old table exists
    const tableExists = await queryInterface.sequelize.query(
      `SELECT EXISTS (
        SELECT FROM information_schema.tables
        WHERE table_schema = 'public'
        AND table_name = 'ui_elements'
      );`,
      { type: Sequelize.QueryTypes.SELECT },
    );

    if (!tableExists[0]?.exists) {
      console.log('Table ui_elements does not exist, skipping rename');
      return;
    }

    // Check if new table already exists (migration may have been partially run)
    const newTableExists = await queryInterface.sequelize.query(
      `SELECT EXISTS (
        SELECT FROM information_schema.tables
        WHERE table_schema = 'public'
        AND table_name = 'element_type_defaults'
      );`,
      { type: Sequelize.QueryTypes.SELECT },
    );

    if (newTableExists[0]?.exists) {
      console.log(
        'Table element_type_defaults already exists, skipping rename',
      );
      return;
    }

    // Rename table
    await queryInterface.renameTable('ui_elements', 'element_type_defaults');

    // Update any sequences (PostgreSQL auto-creates these for SERIAL columns, but UUID doesn't need them)
    // No sequence updates needed since we use UUID primary keys

    console.log('Successfully renamed ui_elements to element_type_defaults');
  },

  async down(queryInterface, Sequelize) {
    // Check if new table exists
    const tableExists = await queryInterface.sequelize.query(
      `SELECT EXISTS (
        SELECT FROM information_schema.tables
        WHERE table_schema = 'public'
        AND table_name = 'element_type_defaults'
      );`,
      { type: Sequelize.QueryTypes.SELECT },
    );

    if (!tableExists[0]?.exists) {
      console.log(
        'Table element_type_defaults does not exist, skipping rollback',
      );
      return;
    }

    // Rename table back
    await queryInterface.renameTable('element_type_defaults', 'ui_elements');

    console.log(
      'Successfully rolled back: renamed element_type_defaults to ui_elements',
    );
  },
};
