'use strict';

/**
 * Migration: Drop page_links table
 *
 * This table was designed for storing navigation links between pages but was never used.
 * Navigation targets are stored in tour_pages.ui_schema_json as targetPageSlug 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_links',
    );
    const count = parseInt(results[0].count, 10);

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

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

  async down(queryInterface, Sequelize) {
    // Recreate the page_links table
    await queryInterface.createTable('page_links', {
      id: {
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4,
        primaryKey: true,
      },
      from_pageId: {
        type: Sequelize.UUID,
        allowNull: true,
        references: {
          model: 'tour_pages',
          key: 'id',
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE',
      },
      to_pageId: {
        type: Sequelize.UUID,
        allowNull: true,
        references: {
          model: 'tour_pages',
          key: 'id',
        },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL',
      },
      transitionId: {
        type: Sequelize.UUID,
        allowNull: true,
        references: {
          model: 'transitions',
          key: 'id',
        },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL',
      },
      is_active: {
        type: Sequelize.BOOLEAN,
        defaultValue: 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,
      },
    });
  },
};
