'use strict';

/**
 * Migration: Drop page_elements table
 *
 * This table was designed for storing individual page elements but was never used.
 * All element data is stored in tour_pages.ui_schema_json instead.
 */
module.exports = {
  async up(queryInterface, _Sequelize) {
    // Verify the table is empty before dropping
    const [results] = await queryInterface.sequelize.query(
      'SELECT COUNT(*) as count FROM page_elements',
    );
    const count = parseInt(results[0].count, 10);

    if (count > 0) {
      throw new Error(
        `Cannot drop page_elements table: it contains ${count} records. Please migrate or delete them first.`,
      );
    }

    await queryInterface.dropTable('page_elements');
    console.log('Dropped page_elements table (was empty)');
  },

  async down(queryInterface, Sequelize) {
    // Recreate the page_elements table
    await queryInterface.createTable('page_elements', {
      id: {
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4,
        primaryKey: true,
      },
      pageId: {
        type: Sequelize.UUID,
        allowNull: false,
        references: {
          model: 'tour_pages',
          key: 'id',
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE',
      },
      element_type: {
        type: Sequelize.STRING,
        allowNull: false,
      },
      xPercent: {
        type: Sequelize.DECIMAL(10, 6),
        allowNull: true,
      },
      yPercent: {
        type: Sequelize.DECIMAL(10, 6),
        allowNull: true,
      },
      content_json: {
        type: Sequelize.TEXT,
        allowNull: true,
      },
      createdAt: {
        type: Sequelize.DATE,
        allowNull: false,
      },
      updatedAt: {
        type: Sequelize.DATE,
        allowNull: false,
      },
      deletedAt: {
        type: Sequelize.DATE,
        allowNull: true,
      },
      createdById: {
        type: Sequelize.UUID,
        allowNull: true,
        references: {
          model: 'users',
          key: 'id',
        },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL',
      },
      updatedById: {
        type: Sequelize.UUID,
        allowNull: true,
        references: {
          model: 'users',
          key: 'id',
        },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL',
      },
      importHash: {
        type: Sequelize.STRING(255),
        allowNull: true,
        unique: true,
      },
    });
  },
};
