import { DataTypes, type QueryInterface } from 'sequelize';

async function columnExists(
  queryInterface: QueryInterface,
  table: string,
  column: string,
): Promise<boolean> {
  const [results] = await queryInterface.sequelize.query(`
    SELECT 1 FROM information_schema.columns
    WHERE table_name = '${table}' AND column_name = '${column}'
  `);
  return (results as unknown[]).length > 0;
}

export default {
  up: async (queryInterface: QueryInterface) => {
    if (!(await columnExists(queryInterface, 'communication_events', 'canceledEventId'))) {
      await queryInterface.addColumn('communication_events', 'canceledEventId', {
        type: DataTypes.UUID,
        allowNull: true,
      });
    }
  },

  down: async (queryInterface: QueryInterface) => {
    if (await columnExists(queryInterface, 'communication_events', 'canceledEventId')) {
      await queryInterface.removeColumn('communication_events', 'canceledEventId');
    }
  },
};
