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

/**
 * Direct 1:1 messages between a staff member (teacher / office_manager) and a
 * guardian. A conversation is the unordered pair {senderId, recipientId}; both
 * parties are discovered through a shared student (`studentId` is the connecting
 * context). Access is membership-based — a user only ever reads rows where they
 * are the sender or the recipient, so conversations are naturally isolated.
 * App-level UUIDs, no DB-level FK constraints (consistent with the schema).
 * Idempotent.
 */
async function tableExists(
  queryInterface: QueryInterface,
  table: string,
): Promise<boolean> {
  const [results] = await queryInterface.sequelize.query(`
    SELECT 1 FROM information_schema.tables WHERE table_name = '${table}'
  `);
  return (results as unknown[]).length > 0;
}

export default {
  up: async (queryInterface: QueryInterface) => {
    if (!(await tableExists(queryInterface, 'direct_messages'))) {
      await queryInterface.createTable('direct_messages', {
        id: {
          type: DataTypes.UUID,
          defaultValue: DataTypes.UUIDV4,
          primaryKey: true,
        },
        senderId: { type: DataTypes.UUID, allowNull: false },
        recipientId: { type: DataTypes.UUID, allowNull: false },
        studentId: { type: DataTypes.UUID, allowNull: true },
        body: { type: DataTypes.TEXT, allowNull: false },
        readAt: { type: DataTypes.DATE, allowNull: true },
        organizationId: { type: DataTypes.UUID, allowNull: true },
        createdById: { type: DataTypes.UUID, allowNull: true },
        updatedById: { type: DataTypes.UUID, allowNull: true },
        createdAt: { type: DataTypes.DATE, allowNull: false },
        updatedAt: { type: DataTypes.DATE, allowNull: false },
        deletedAt: { type: DataTypes.DATE, allowNull: true },
      });
    }
  },

  down: async (queryInterface: QueryInterface) => {
    if (await tableExists(queryInterface, 'direct_messages')) {
      await queryInterface.dropTable('direct_messages');
    }
  },
};
