/**
 * Remote machine (relay) RPC handlers.
 */

import type { RelayClient } from "../relay-client.ts";
import type { SettingsDb } from "../settings-db.ts";

export function createRemoteHandlers(relayClient: RelayClient, settingsDb?: SettingsDb) {
  return {
    // Fix #4 (Codex audit): relay-client.connect() now returns { ok, machineId, error }
    "remote.connect": async ({ url, token, label }: { url: string; token: string; label?: string }) => {
      try {
        const result = await relayClient.connect(url, token, label);
        return result;
      } catch (err) {
        const error = err instanceof Error ? err.message : String(err);
        console.error("[remote.connect]", err);
        return { ok: false, error };
      }
    },

    "remote.disconnect": ({ machineId }: { machineId: string }) => {
      try {
        relayClient.disconnect(machineId);
        return { ok: true };
      } catch (err) {
        const error = err instanceof Error ? err.message : String(err);
        console.error("[remote.disconnect]", err);
        return { ok: false, error };
      }
    },

    // Fix #6 (Codex audit): Add remote.remove RPC that disconnects AND deletes
    "remote.remove": ({ machineId }: { machineId: string }) => {
      try {
        relayClient.removeMachine(machineId);
        return { ok: true };
      } catch (err) {
        const error = err instanceof Error ? err.message : String(err);
        console.error("[remote.remove]", err);
        return { ok: false, error };
      }
    },

    "remote.list": () => {
      try {
        return { machines: relayClient.listMachines() };
      } catch (err) {
        console.error("[remote.list]", err);
        return { machines: [] };
      }
    },

    "remote.send": ({ machineId, command, payload }: { machineId: string; command: string; payload: Record<string, unknown> }) => {
      try {
        relayClient.sendCommand(machineId, command, payload);
        return { ok: true };
      } catch (err) {
        const error = err instanceof Error ? err.message : String(err);
        console.error("[remote.send]", err);
        return { ok: false, error };
      }
    },

    "remote.status": ({ machineId }: { machineId: string }) => {
      try {
        const info = relayClient.getStatus(machineId);
        if (!info) {
          return { status: "disconnected" as const, latencyMs: null, error: "Machine not found" };
        }
        return { status: info.status, latencyMs: info.latencyMs };
      } catch (err) {
        const error = err instanceof Error ? err.message : String(err);
        console.error("[remote.status]", err);
        return { status: "error" as const, latencyMs: null, error };
      }
    },

    // Feature 3: Remote credential vault
    "remote.getStoredCredentials": () => {
      if (!settingsDb) return { credentials: [] };
      return { credentials: settingsDb.listRelayCredentials() };
    },

    "remote.storeCredential": ({ url, token, label }: { url: string; token: string; label?: string }) => {
      if (!settingsDb) return { ok: false };
      try { settingsDb.storeRelayCredential(url, token, label); return { ok: true }; }
      catch (err) { console.error("[remote.storeCredential]", err); return { ok: false }; }
    },

    "remote.deleteCredential": ({ url }: { url: string }) => {
      if (!settingsDb) return { ok: false };
      try { settingsDb.deleteRelayCredential(url); return { ok: true }; }
      catch (err) { console.error("[remote.deleteCredential]", err); return { ok: false }; }
    },
  };
}
