import type { FastifyInstance } from 'fastify';
import websocket from '@fastify/websocket';
import { config } from '../config.js';
import { devAuth } from '../auth/dev-stub.js';
import { Session } from './session.js';
import { onChangelog } from '../db/notify.js';

const sessions = new Set<Session>();

export async function registerWs(app: FastifyInstance): Promise<void> {
  await app.register(websocket);

  app.get(config.http.wsPath, { websocket: true }, (socket, req) => {
    const actor = devAuth(req);
    const session = new Session(socket, actor);
    sessions.add(session);

    socket.on('message', (buf: Buffer) => {
      void session.handleMessage(buf.toString('utf8'));
    });
    socket.on('close', () => sessions.delete(session));
    socket.on('error', err => {
      console.error('[ws]', session.id, err);
      sessions.delete(session);
    });
  });

  // Раздаём changelog всем подписанным сессиям.
  onChangelog(n => {
    for (const s of sessions) {
      s.push({ type: 'changelog', id: n.id, table: n.t, op: n.op, rowId: n.rid });
    }
  });
}
