/**
 * Migration: Add unique constraint to builds table
 * Ensures that the same build name cannot be created multiple times for the same organization
 * This prevents duplicate builds when parallel tests use the same buildName
 */

'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    // First, remove any duplicate builds keeping only the most recent one
    // Duplicates are identified by same name and organization_id
    await queryInterface.sequelize.query(`
      DELETE FROM builds b1
      USING builds b2
      WHERE b1.id < b2.id
        AND b1.name = b2.name
        AND b1.name IS NOT NULL
        AND b1.organization_id = b2.organization_id;
    `);

    // Add unique constraint on name + organization_id combination
    // Note: In SQL, NULL values in unique constraints are considered distinct,
    // so multiple NULL names are allowed, but non-NULL names must be unique per organization
    // This is the desired behavior: builds without names can have NULL, but named builds must be unique
    try {
      await queryInterface.addConstraint('builds', {
        fields: ['name', 'organization_id'],
        type: 'unique',
        name: 'builds_name_organization_id_unique',
      });
    } catch (error) {
      // If constraint already exists or other error, log and continue
      console.log('⚠️  Could not add unique constraint (may already exist):', error.message);
    }

    console.log('✅ Added unique constraint on builds (name, organization_id)');
  },

  async down(queryInterface, Sequelize) {
    // Remove unique constraint
    try {
      await queryInterface.removeConstraint('builds', 'builds_name_organization_id_unique');
      console.log('⬇️  Removed unique constraint from builds (name, organization_id)');
    } catch (error) {
      // Constraint might not exist if it wasn't created
      console.log('ℹ️  Unique constraint may not exist, skipping removal');
    }
  },
};
