/**
 * Migration: Add unique constraint to devices table
 * Ensures that the same device (udid) cannot be registered multiple times for the same node
 */

'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    // First, remove any duplicate devices keeping only the most recent one
    await queryInterface.sequelize.query(`
      DELETE FROM devices d1
      USING devices d2
      WHERE d1.id < d2.id
        AND d1.udid = d2.udid
        AND d1.node_id = d2.node_id;
    `);

    // Add unique constraint on udid + node_id combination
    await queryInterface.addConstraint('devices', {
      fields: ['udid', 'node_id'],
      type: 'unique',
      name: 'devices_udid_node_id_unique',
    });

    console.log('✅ Added unique constraint on devices (udid, node_id)');
  },

  async down(queryInterface, Sequelize) {
    // Remove unique constraint
    await queryInterface.removeConstraint('devices', 'devices_udid_node_id_unique');
    console.log('⬇️  Removed unique constraint from devices (udid, node_id)');
  },
};
