/**
 * Tauri adapter for {@link TemplateGateway} (L7).
 *
 * Commands use snake_case (Tauri convention); payload keys are camelCase
 * (matching the backend DTO `#[serde(rename_all = "camelCase")]`), consistent
 * with the other adapters in this directory.
 *
 * NOTE: The Tauri commands wired here are defined in the backend `app-tauri`
 * crate and will be registered in a subsequent lot. This adapter is complete
 * on the frontend side; the mock gateway covers tests and offline dev today.
 */

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

import type { Agent, AgentDrift, Template } from "@/domain";
import type { CreateTemplateInput, TemplateGateway } from "@/ports";

export class TauriTemplateGateway implements TemplateGateway {
  listTemplates(): Promise<Template[]> {
    return invoke<Template[]>("list_templates");
  }

  createTemplate(input: CreateTemplateInput): Promise<Template> {
    return invoke<Template>("create_template", {
      request: {
        name: input.name,
        content: input.content,
        defaultProfileId: input.defaultProfileId,
      },
    });
  }

  updateTemplate(templateId: string, content: string): Promise<Template> {
    return invoke<Template>("update_template", {
      request: { templateId, content },
    });
  }

  async deleteTemplate(templateId: string): Promise<void> {
    await invoke("delete_template", { templateId });
  }

  createAgentFromTemplate(
    projectId: string,
    templateId: string,
    opts?: { name?: string; synchronized?: boolean },
  ): Promise<Agent> {
    return invoke<Agent>("create_agent_from_template", {
      request: {
        projectId,
        templateId,
        name: opts?.name ?? null,
        synchronized: opts?.synchronized ?? true,
      },
    });
  }

  detectDrift(projectId: string): Promise<AgentDrift[]> {
    return invoke<AgentDrift[]>("detect_agent_drift", { projectId });
  }

  syncAgent(
    projectId: string,
    agentId: string,
  ): Promise<{ synced: boolean; version: number | null }> {
    return invoke<{ synced: boolean; version: number | null }>(
      "sync_agent_with_template",
      { request: { projectId, agentId } },
    );
  }
}
