/* eslint-disable no-console */
import { DataTypes, QueryTypes } from 'sequelize';
import { Migration } from '../migrate';

export const up: Migration = async ({ context }) => {
  try {
    await context.changeColumn('customers', 'did', {
      type: DataTypes.STRING(40),
      allowNull: false,
      unique: true,
    });

    console.log('Successfully added unique constraint to customers.did');
  } catch (error) {
    try {
      const duplicates = await context.sequelize.query(
        `SELECT did, COUNT(*) as count 
         FROM customers 
         GROUP BY did 
         HAVING COUNT(*) > 1
         LIMIT 5`,
        { type: QueryTypes.SELECT }
      );

      if (duplicates.length > 0) {
        console.warn('Found duplicate DIDs in customers table (showing first 5):', duplicates);
        console.warn('Skipping unique constraint addition. Please clean up duplicate data manually if needed.');
      } else {
        console.error('Failed to add unique constraint for unknown reason:', error.message);
      }
    } catch (checkError) {
      console.error('Failed to check for duplicates:', checkError.message);
    }
  }
};

export const down: Migration = async ({ context }) => {
  try {
    await context.changeColumn('customers', 'did', {
      type: DataTypes.STRING(40),
      allowNull: false,
      unique: false,
    });

    console.log('Successfully removed unique constraint from customers.did');
  } catch (error) {
    console.warn('Failed to remove unique constraint from customers.did:', error.message);
  }
};
