/**
 * Tauri adapter for the public plugin command-task SDK facade (#125).
 */

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

import type { PluginCommandTask } from "@/domain";
import type { PluginRunCommandInput, PluginTaskGateway, PluginTaskStatusInput } from "@/ports";

type PluginCommandTaskDto = Omit<
  PluginCommandTask,
  "exitCode" | "summary" | "stdoutTail" | "stderrTail"
> & {
  exitCode?: number | null;
  summary?: string | null;
  stdoutTail?: string | null;
  stderrTail?: string | null;
};

function normalizeTask(task: PluginCommandTaskDto): PluginCommandTask {
  return {
    ...task,
    exitCode: task.exitCode ?? null,
    summary: task.summary ?? null,
    stdoutTail: task.stdoutTail ?? null,
    stderrTail: task.stderrTail ?? null,
  };
}

export class TauriPluginTaskGateway implements PluginTaskGateway {
  async runCommand(input: PluginRunCommandInput): Promise<PluginCommandTask> {
    const task = await invoke<PluginCommandTaskDto>("plugin_task_run_command", { input });
    return normalizeTask(task);
  }

  async getStatus(input: PluginTaskStatusInput): Promise<PluginCommandTask | null> {
    const task = await invoke<PluginCommandTaskDto | null>("plugin_task_get_status", { input });
    return task ? normalizeTask(task) : null;
  }
}
