import { ShadeFileRpcChannel } from '../rpc/channel.js';
import type { FileHandler } from '../server/handler.js';

/**
 * Connect a `FileHandler` to a `ShadeFileRpcChannel`. Returns an unsubscribe
 * function that detaches the handler. Throws if a handler is already wired
 * on this channel.
 *
 * The wiring:
 *  - On `request` envelopes: invoke `handler.handleRequest`, then send the
 *    returned response/error envelope back to the requester.
 *  - On `cancel` envelopes: forward to `handler.handleCancel`.
 */
export function attachFileHandler(
  channel: ShadeFileRpcChannel,
  handler: FileHandler,
): () => void {
  const previous = channel.setHooks({
    onRequest: async (from, env) => {
      const response = await handler.handleRequest(from, env.envelope);
      try {
        await channel.send(from, response);
      } catch (err) {
        console.error('[shade-files] failed to send response:', err);
      }
    },
    onCancel: (from, env) => {
      handler.handleCancel(from, env.envelope);
    },
  });
  return () => {
    handler.destroy();
    channel.setHooks(previous);
  };
}
