import type { GatewayRequest, OutboundMessage } from '../protocol.js';
import { makeResponse, makeError, ErrorCode } from '../protocol.js';
import type { PairingManager } from '../../channels/pairing.js';

export interface PairingHandlerDeps {
  pairingManager: PairingManager;
}

export function createPairingHandlers(deps: PairingHandlerDeps) {
  return {
    'pairing.generate': async (request: GatewayRequest): Promise<OutboundMessage> => {
      const label = request.params?.label as string | undefined;
      const code = deps.pairingManager.generateCode(label);
      const pending = deps.pairingManager.listPendingCodes();
      const entry = pending.find(p => p.code === code);

      return makeResponse(request.id, {
        code,
        expiresAt: entry?.expiresAt ?? null,
      });
    },

    'pairing.list': async (request: GatewayRequest): Promise<OutboundMessage> => {
      return makeResponse(request.id, {
        pending: deps.pairingManager.listPendingCodes(),
        approved: deps.pairingManager.listApproved(),
      });
    },

    'pairing.revoke': async (request: GatewayRequest): Promise<OutboundMessage> => {
      const channel = request.params?.channel as string | undefined;
      const senderId = request.params?.senderId as string | undefined;

      if (!channel || !senderId) {
        return makeError(request.id, ErrorCode.InvalidRequest, 'Missing required params: channel, senderId');
      }

      const revoked = deps.pairingManager.revokeApproval(channel, senderId);
      return makeResponse(request.id, { revoked });
    },
  };
}
