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

/**
 * Exact-tenant walk-through check-ins (WS, scope map). A boss evaluates only
 * their own tenant's staff — org/school/campus each own theirs. Adds nullable
 * `schoolId` and `classId` (the owning tenant is the most specific non-null of
 * (classId, campusId, schoolId, organizationId)). 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, 'walkthrough_checkins', 'schoolId'))) {
      await queryInterface.addColumn('walkthrough_checkins', 'schoolId', {
        type: DataTypes.UUID,
        allowNull: true,
      });
    }
    if (!(await columnExists(queryInterface, 'walkthrough_checkins', 'classId'))) {
      await queryInterface.addColumn('walkthrough_checkins', 'classId', {
        type: DataTypes.UUID,
        allowNull: true,
      });
    }
  },

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