import type {
  WgCreateInterface,
  WgCreatePeerRequest,
  WgExportRequest,
  WgExportResponse,
  WgImportRequest,
  WgImportResponse,
  WgListResponse,
  WgPatchInterface,
  WgPatchPeer,
} from "@mmapp/contracts/wireguard"
import { requestJson } from "@/shared/api/http-client"

export async function listWireGuard(
  baseUrl: string,
  opts?: { serverId?: string; includePrivateKey?: boolean },
): Promise<WgListResponse> {
  const q = new URLSearchParams()
  if (opts?.serverId) q.set("serverId", opts.serverId)
  if (opts?.includePrivateKey) q.set("includePrivateKey", "1")
  const qs = q.toString()
  return requestJson<WgListResponse>(baseUrl, `/api/wireguard${qs ? `?${qs}` : ""}`)
}

export async function createWireGuardInterface(
  baseUrl: string,
  payload: WgCreateInterface,
): Promise<unknown> {
  return requestJson(baseUrl, "/api/wireguard/interfaces", {
    method: "POST",
    body: JSON.stringify(payload),
  })
}

export async function patchWireGuardInterface(
  baseUrl: string,
  serverId: string,
  rosId: string,
  payload: WgPatchInterface,
): Promise<{ ok: boolean }> {
  return requestJson(baseUrl, `/api/wireguard/interfaces/${encodeURIComponent(serverId)}/${encodeURIComponent(rosId)}`, {
    method: "PATCH",
    body: JSON.stringify(payload),
  })
}

export async function deleteWireGuardInterface(
  baseUrl: string,
  serverId: string,
  rosId: string,
): Promise<{ ok: boolean }> {
  return requestJson(baseUrl, `/api/wireguard/interfaces/${encodeURIComponent(serverId)}/${encodeURIComponent(rosId)}`, {
    method: "DELETE",
  })
}

export async function createWireGuardPeer(
  baseUrl: string,
  payload: WgCreatePeerRequest,
): Promise<{ ok: boolean }> {
  return requestJson(baseUrl, "/api/wireguard/peers", {
    method: "POST",
    body: JSON.stringify(payload),
  })
}

export async function patchWireGuardPeer(
  baseUrl: string,
  serverId: string,
  rosId: string,
  payload: WgPatchPeer,
): Promise<{ ok: boolean }> {
  return requestJson(baseUrl, `/api/wireguard/peers/${encodeURIComponent(serverId)}/${encodeURIComponent(rosId)}`, {
    method: "PATCH",
    body: JSON.stringify(payload),
  })
}

export async function deleteWireGuardPeer(
  baseUrl: string,
  serverId: string,
  rosId: string,
): Promise<{ ok: boolean }> {
  return requestJson(baseUrl, `/api/wireguard/peers/${encodeURIComponent(serverId)}/${encodeURIComponent(rosId)}`, {
    method: "DELETE",
  })
}

export async function importWireGuard(
  baseUrl: string,
  payload: WgImportRequest,
): Promise<WgImportResponse> {
  return requestJson(baseUrl, "/api/wireguard/import", {
    method: "POST",
    body: JSON.stringify(payload),
  })
}

export async function exportWireGuard(
  baseUrl: string,
  payload: WgExportRequest,
): Promise<WgExportResponse> {
  return requestJson(baseUrl, "/api/wireguard/export", {
    method: "POST",
    body: JSON.stringify(payload),
  })
}
