/**
 * Tauri adapter for {@link WorkStateGateway}.
 *
 * This is the only frontend place that knows the `get_project_work_state`
 * command name; features consume the gateway port through DI.
 */

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

import type { ProjectWorkState } from "@/domain";
import type { BackgroundTaskAttachment, WorkStateGateway } from "@/ports";
import { normalizeProjectWorkState } from "./workStateNormalization";

interface AttachBackgroundTaskResponse {
  taskId: string;
  scrollback: number[];
  live: boolean;
}

export class TauriWorkStateGateway implements WorkStateGateway {
  async getProjectWorkState(projectId: string): Promise<ProjectWorkState> {
    const state = await invoke<unknown>("get_project_work_state", { projectId });
    return normalizeProjectWorkState(state);
  }

  async attachBackgroundTask(
    taskId: string,
    onData: (bytes: Uint8Array) => void,
  ): Promise<BackgroundTaskAttachment> {
    const channel = new Channel<number[]>();
    channel.onmessage = (chunk) => onData(Uint8Array.from(chunk));
    const res = await invoke<AttachBackgroundTaskResponse>("attach_background_task", {
      taskId,
      onOutput: channel,
    });
    return {
      taskId: res.taskId,
      scrollback: Uint8Array.from(res.scrollback),
      live: res.live,
      detach: () => {
        channel.onmessage = () => {};
      },
    };
  }

  async cancelBackgroundTask(taskId: string): Promise<void> {
    await invoke<unknown>("cancel_background_task", { taskId });
  }

  async retryBackgroundTask(taskId: string): Promise<void> {
    await invoke<unknown>("retry_background_task", { taskId });
  }
}
