'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    // Create wda_device_mappings table
    await queryInterface.createTable('wda_device_mappings', {
      id: {
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4,
        primaryKey: true,
      },
      wda_id: {
        type: Sequelize.UUID,
        allowNull: false,
        references: {
          model: 'wda',
          key: 'id',
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE',
        comment: 'Reference to the WDA file',
      },
      device_id: {
        type: Sequelize.UUID,
        allowNull: false,
        references: {
          model: 'devices',
          key: 'id',
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE',
        comment: 'Reference to the device',
      },
      created_by: {
        type: Sequelize.UUID,
        allowNull: false,
        references: {
          model: 'users',
          key: 'id',
        },
        comment: 'User who created this mapping',
      },
      created_at: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
      },
      updated_at: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
      },
    });

    // Add unique constraint: one WDA can be mapped to one device (one-to-one)
    await queryInterface.addConstraint('wda_device_mappings', {
      fields: ['wda_id', 'device_id'],
      type: 'unique',
      name: 'unique_wda_device_mapping',
    });

    // Add indexes for better query performance
    await queryInterface.addIndex('wda_device_mappings', ['wda_id'], {
      name: 'idx_wda_device_mappings_wda_id',
    });

    await queryInterface.addIndex('wda_device_mappings', ['device_id'], {
      name: 'idx_wda_device_mappings_device_id',
    });

    await queryInterface.addIndex('wda_device_mappings', ['created_by'], {
      name: 'idx_wda_device_mappings_created_by',
    });
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.dropTable('wda_device_mappings');
  },
};
