'use strict';

async function addColumnIfNotExists(queryInterface, tableName, columnName, columnDefinition) {
  const tableDescription = await queryInterface.describeTable(tableName);
  if (!tableDescription[columnName]) {
    await queryInterface.addColumn(tableName, columnName, columnDefinition);
  }
}

module.exports = {
  async up(queryInterface, Sequelize) {
    // Session: interactive attach tracking
    await addColumnIfNotExists(queryInterface, 'sessions', 'interactive_attached_by', {
      type: Sequelize.UUID,
      allowNull: true,
      references: {
        model: 'users',
        key: 'id',
      },
    });

    await addColumnIfNotExists(queryInterface, 'sessions', 'interactive_attached_at', {
      type: Sequelize.DATE,
      allowNull: true,
    });

    // WebRtcConnection: viewer peer tracking
    await addColumnIfNotExists(queryInterface, 'webrtc_connections', 'peer_session_id', {
      type: Sequelize.UUID,
      allowNull: true,
    });

    await addColumnIfNotExists(queryInterface, 'webrtc_connections', 'automation_session_id', {
      type: Sequelize.UUID,
      allowNull: true,
      references: {
        model: 'sessions',
        key: 'id',
      },
    });

    await addColumnIfNotExists(queryInterface, 'webrtc_connections', 'is_viewer', {
      type: Sequelize.BOOLEAN,
      allowNull: false,
      defaultValue: false,
    });

    await addColumnIfNotExists(queryInterface, 'webrtc_connections', 'device_mjpeg_url', {
      type: Sequelize.TEXT,
      allowNull: true,
    });

    await addColumnIfNotExists(queryInterface, 'webrtc_connections', 'device_appium_url', {
      type: Sequelize.TEXT,
      allowNull: true,
    });
  },

  async down(queryInterface) {
    await queryInterface.removeColumn('webrtc_connections', 'device_appium_url');
    await queryInterface.removeColumn('webrtc_connections', 'device_mjpeg_url');
    await queryInterface.removeColumn('webrtc_connections', 'is_viewer');
    await queryInterface.removeColumn('webrtc_connections', 'automation_session_id');
    await queryInterface.removeColumn('webrtc_connections', 'peer_session_id');
    await queryInterface.removeColumn('sessions', 'interactive_attached_at');
    await queryInterface.removeColumn('sessions', 'interactive_attached_by');
  },
};
