/**
 * commands.ts — Thin adapter-local command handler for {{DISPLAY_NAME}}
 *
 * Only handles commands that require direct upstream service access
 * (/restart, /login). All other commands are forwarded to the AIBroker
 * hub daemon via route_message in index.ts.
 */

import { log } from "aibroker";
import { sendText } from "./send.js";

/**
 * Create the local message handler for adapter-specific commands.
 *
 * Only /restart and /login are handled here. Everything else should have
 * been routed to the hub by index.ts — this handler is the fallback for
 * commands that need direct adapter access.
 */
export function createMessageHandler(): (text: string, timestamp: number) => void {
  return function handleMessage(text: string, _timestamp: number): void {
    const trimmed = text.trim();

    if (trimmed === "/restart") {
      log("/restart: watcher restart requested");
      sendText("Restarting {{ADAPTER_NAME}} watcher...").catch(() => {});
      setTimeout(() => {
        log("/restart: exiting — process manager will restart us");
        process.exit(0);
      }, 1500);
      return;
    }

    // /login is handled via the triggerLogin callback in index.ts,
    // not here. This is just a safety net.
    if (trimmed === "/login") {
      sendText("Use the login flow — handled by the watcher.").catch(() => {});
      return;
    }

    // Everything else should have gone to the hub. If we get here,
    // something went wrong with routing.
    log(`[{{ADAPTER_NAME}}] commands.ts: unexpected local message: ${trimmed.slice(0, 60)}`);
  };
}
