import { invoke } from "@tauri-apps/api/tauri";

function assertPayload(payload) {
  if (payload && typeof payload === "object") return payload;
  throw new Error("App payload must be an object");
}

async function saveApiKey(token) {
  if (!token || typeof token !== "string") throw new Error("token is required");
  return invoke("save_api_key", { token });
}

async function persistApp(app) {
  const valid = assertPayload(app);
  if (!valid.id) throw new Error("app.id is required");
  return invoke("persist_app", { app: valid });
}

async function listApps() {
  return invoke("list_apps");
}

async function syncApp(appId) {
  if (!appId) throw new Error("appId is required");
  return invoke("sync_app", { appId });
}

async function runOpencodeTask(appId, taskName, args = []) {
  if (!appId) throw new Error("appId is required");
  if (!taskName) throw new Error("taskName is required");
  return invoke("run_opencode_task", { appId, taskName, args });
}

window.windowsAppBridge = {
  saveApiKey,
  persistApp,
  listApps,
  syncApp,
  runOpencodeTask,
};
