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

/**
 * Internal alerts target exact audience tiers. The tenant ids identify the
 * selected organization/school/campus; targetLevel distinguishes platform
 * system-only alerts from platform all-user broadcasts.
 */
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', 'targetLevel'))) {
      await queryInterface.addColumn('communication_events', 'targetLevel', {
        type: DataTypes.TEXT,
        allowNull: false,
        defaultValue: 'campus',
      });
    }
  },

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