import { type Shortcut } from "@/types/proto/api/v1/shortcut_service_pb";
import { fetchJson, parseResourceId } from "./apiClient";
import { shortcutFromApi } from "./converters";
import type { ApiShortcut } from "./types";

export const shortcutServiceClient = {
  async listShortcuts(_request?: { parent?: string }): Promise<{ shortcuts: Shortcut[] }> {
    void _request;
    const data = await fetchJson<ApiShortcut[]>("/shortcuts", { method: "GET" });
    const shortcuts = Array.isArray(data) ? data.map(shortcutFromApi) : [];
    return { shortcuts };
  },
  async createShortcut(request: { shortcut?: Shortcut }): Promise<Shortcut> {
    const shortcut = request.shortcut;
    if (!shortcut) {
      throw new Error("Missing shortcut payload");
    }
    const payload = {
      name: shortcut.title || "",
      filter: shortcut.filter || "",
    };
    const data = await fetchJson<ApiShortcut>("/shortcuts", { method: "POST", body: payload });
    return shortcutFromApi(data);
  },
  async updateShortcut(request: { shortcut?: Shortcut }): Promise<Shortcut> {
    const shortcut = request.shortcut;
    if (!shortcut?.name) {
      throw new Error("Missing shortcut name");
    }
    const shortcutId = parseResourceId(shortcut.name);
    const payload = {
      name: shortcut.title || "",
      filter: shortcut.filter || "",
    };
    const data = await fetchJson<ApiShortcut>(`/shortcuts/${shortcutId}`, { method: "PATCH", body: payload });
    return shortcutFromApi(data);
  },
  async deleteShortcut(request: { name: string }): Promise<void> {
    const shortcutId = parseResourceId(request.name);
    await fetchJson(`/shortcuts/${shortcutId}`, { method: "DELETE" });
  },
};

