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

import type {
  EffectivePermissions,
  McpToolPolicy,
  PermissionSet,
  ProjectMcpToolPermissions,
  ProjectPermissions,
} from "@/domain";
import type { PermissionGateway } from "@/ports";

/** Tauri-backed permissions gateway. */
export class TauriPermissionGateway implements PermissionGateway {
  getProjectPermissions(projectId: string): Promise<ProjectPermissions> {
    return invoke<ProjectPermissions>("get_project_permissions", { projectId });
  }

  updateProjectPermissions(
    projectId: string,
    permissions: PermissionSet | null,
  ): Promise<ProjectPermissions> {
    return invoke<ProjectPermissions>("update_project_permissions", {
      request: { projectId, permissions },
    });
  }

  updateAgentPermissions(
    projectId: string,
    agentId: string,
    permissions: PermissionSet | null,
  ): Promise<ProjectPermissions> {
    return invoke<ProjectPermissions>("update_agent_permissions", {
      request: { projectId, agentId, permissions },
    });
  }

  resolveAgentPermissions(
    projectId: string,
    agentId: string,
  ): Promise<EffectivePermissions | null> {
    return invoke<EffectivePermissions | null>("resolve_agent_permissions", {
      request: { projectId, agentId },
    });
  }

  getMcpToolPermissions(projectId: string): Promise<ProjectMcpToolPermissions> {
    return invoke<ProjectMcpToolPermissions>("get_mcp_tool_permissions", {
      projectId,
    });
  }

  updateProjectMcpToolPermissions(
    projectId: string,
    policy: McpToolPolicy | null,
  ): Promise<ProjectMcpToolPermissions> {
    return invoke<ProjectMcpToolPermissions>(
      "update_project_mcp_tool_permissions",
      { request: { projectId, policy } },
    );
  }

  updateAgentMcpToolPermissions(
    projectId: string,
    agentId: string,
    policy: McpToolPolicy | null,
  ): Promise<ProjectMcpToolPermissions> {
    return invoke<ProjectMcpToolPermissions>(
      "update_agent_mcp_tool_permissions",
      { request: { projectId, agentId, policy } },
    );
  }
}
