'use strict';

/**
 * Migration: Preserve sessions when device is deleted
 *
 * Previously, deleting a device would CASCADE delete all associated sessions,
 * losing valuable test history. This migration changes the behavior to SET NULL,
 * so sessions are preserved and only the device reference becomes NULL.
 *
 * Uses raw SQL because Sequelize's changeColumn doesn't properly handle
 * foreign key constraint modifications.
 */

/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up(queryInterface, Sequelize) {
    console.log('🔄 Updating sessions table to preserve sessions when device is deleted...');

    // Step 1: Make the column nullable (if not already)
    await queryInterface.sequelize
      .query(
        `
      ALTER TABLE sessions ALTER COLUMN device_id DROP NOT NULL;
    `
      )
      .catch(() => {
        // Column might already be nullable, that's fine
        console.log('  ℹ️  device_id column already nullable or does not exist');
      });

    // Step 2: Drop any existing device_id constraints (handles duplicates too)
    await queryInterface.sequelize.query(`
      ALTER TABLE sessions DROP CONSTRAINT IF EXISTS sessions_device_id_fkey;
    `);

    await queryInterface.sequelize.query(`
      ALTER TABLE sessions DROP CONSTRAINT IF EXISTS sessions_device_id_fkey1;
    `);

    // Step 3: Add the new constraint with SET NULL behavior
    await queryInterface.sequelize.query(`
      ALTER TABLE sessions 
      ADD CONSTRAINT sessions_device_id_fkey 
      FOREIGN KEY (device_id) 
      REFERENCES devices(id) 
      ON UPDATE CASCADE 
      ON DELETE SET NULL;
    `);

    console.log(
      '✅ Sessions will now be preserved when device is deleted (device_id becomes NULL)'
    );
  },

  async down(queryInterface, Sequelize) {
    console.log('🔄 Reverting: Sessions will be deleted when device is deleted...');

    // First, delete sessions that have NULL device_id (can't add NOT NULL constraint otherwise)
    const [results] = await queryInterface.sequelize.query(`
      SELECT COUNT(*) as count FROM sessions WHERE device_id IS NULL;
    `);
    const nullCount = parseInt(results[0].count, 10);

    if (nullCount > 0) {
      console.log(`  ⚠️  Deleting ${nullCount} sessions with NULL device_id...`);
      await queryInterface.sequelize.query(`
        DELETE FROM sessions WHERE device_id IS NULL;
      `);
    }

    // Drop the SET NULL constraint
    await queryInterface.sequelize.query(`
      ALTER TABLE sessions DROP CONSTRAINT IF EXISTS sessions_device_id_fkey;
    `);

    // Make column NOT NULL again
    await queryInterface.sequelize.query(`
      ALTER TABLE sessions ALTER COLUMN device_id SET NOT NULL;
    `);

    // Add back the CASCADE constraint
    await queryInterface.sequelize.query(`
      ALTER TABLE sessions 
      ADD CONSTRAINT sessions_device_id_fkey 
      FOREIGN KEY (device_id) 
      REFERENCES devices(id) 
      ON UPDATE CASCADE 
      ON DELETE CASCADE;
    `);

    console.log('✅ Reverted: Sessions will be deleted when device is deleted');
  },
};
