// Gateway RPC handlers for voice wake routing configuration.
import { ErrorCodes, errorShape } from "../../../packages/gateway-protocol/src/index.js";
import {
  loadVoiceWakeRoutingConfig,
  normalizeVoiceWakeRoutingConfig,
  setVoiceWakeRoutingConfig,
  validateVoiceWakeRoutingConfigInput,
} from "../../infra/voicewake-routing.js";
import type { GatewayRequestHandlers } from "./types.js";

/** Gateway request handlers for reading and updating voice wake routing. */
export const voicewakeRoutingHandlers: GatewayRequestHandlers = {
  "voicewake.routing.get": async ({ respond }) => {
    respond(true, { config: await loadVoiceWakeRoutingConfig() });
  },
  "voicewake.routing.set": async ({ params, respond, context }) => {
    if (
      !params ||
      params.config === null ||
      typeof params.config !== "object" ||
      Array.isArray(params.config)
    ) {
      respond(
        false,
        undefined,
        errorShape(ErrorCodes.INVALID_REQUEST, "voicewake.routing.set requires config: object"),
      );
      return;
    }
    const validated = validateVoiceWakeRoutingConfigInput(params.config);
    if (!validated.ok) {
      respond(false, undefined, errorShape(ErrorCodes.INVALID_REQUEST, validated.message));
      return;
    }
    // Validate first for caller-friendly errors, then normalize before
    // persistence so broadcasts carry the canonical routing shape.
    const normalized = normalizeVoiceWakeRoutingConfig(params.config);
    const config = await setVoiceWakeRoutingConfig(normalized);
    context.broadcastVoiceWakeRoutingChanged(config);
    respond(true, { config });
  },
};
