////
// Dispatch Messages received via WebSocket

import { basename } from "path"
import type { Message } from "./shared/types"
import { runCommand } from "./shell"
import { send } from "./websocket"

export async function dispatchMessage(ws: any, msg: Message) {
  switch (msg.type) {
    case "input":
      await inputMessage(ws, msg); break

    case "save-file":
      await saveFileMessage(ws, msg); break

    default:
      send(ws, { type: "error", data: `unknown message: ${msg.type}` })
  }
}

async function inputMessage(ws: any, msg: Message) {
  const result = await runCommand(msg.session || "", msg.id || "", msg.data as string, ws)

  if (typeof result.output === "object" && "game" in result.output) {
    send(ws, { id: msg.id, type: "game:start", data: result.output.game })
  } else {
    send(ws, { id: msg.id, type: "output", data: result })
  }
}

async function saveFileMessage(ws: any, msg: Message) {
  if (msg.id && typeof msg.data === "string") {
    await Bun.write(msg.id.replace("..", ""), msg.data, { createPath: true })
    send(ws, { type: "output", data: { status: "ok", output: `saved ${basename(msg.id)}` } })
  }
}

