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

/**
 * Per-tenant policy documents (WS-B). Documents become dedicated per tenant
 * level — each of org / school / campus / class owns its own. 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, 'policy_documents', 'schoolId'))) {
      await queryInterface.addColumn('policy_documents', 'schoolId', {
        type: DataTypes.UUID,
        allowNull: true,
      });
    }
    if (!(await columnExists(queryInterface, 'policy_documents', 'classId'))) {
      await queryInterface.addColumn('policy_documents', 'classId', {
        type: DataTypes.UUID,
        allowNull: true,
      });
    }
  },

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