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

/**
 * Exact-tenant internal alerts (scope map). Internal alerts
 * (`communication_events`) are dedicated per tenant — a campus doesn't see
 * org-level alerts and vice-versa. Adds nullable `schoolId` and `classId`.
 * Idempotent.
 */
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', 'schoolId'))) {
      await queryInterface.addColumn('communication_events', 'schoolId', {
        type: DataTypes.UUID,
        allowNull: true,
      });
    }
    if (!(await columnExists(queryInterface, 'communication_events', 'classId'))) {
      await queryInterface.addColumn('communication_events', 'classId', {
        type: DataTypes.UUID,
        allowNull: true,
      });
    }
  },

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