import {
  serverListSchema,
  serverReadSchema,
  testConnectionSchema,
  type ServerCreate,
  type ServerRead,
  type ServerUpdate,
  type TestConnectionRequest,
} from "@mmapp/contracts/servers"
import { requestJson } from "@/shared/api/http-client"

type TestConnectionResponse = {
  success: boolean
  latencyMs?: number
  identity?: string
  version?: string
  boardName?: string
  uptime?: string
  message: string
}

export async function listServers(baseUrl: string): Promise<ServerRead[]> {
  const payload = await requestJson<unknown>(baseUrl, "/api/servers")
  return serverListSchema.parse(payload)
}

export async function getServer(baseUrl: string, id: string): Promise<ServerRead> {
  const payload = await requestJson<unknown>(baseUrl, `/api/servers/${id}`)
  return serverReadSchema.parse(payload)
}

export async function createServer(baseUrl: string, data: ServerCreate): Promise<ServerRead> {
  const payload = await requestJson<unknown>(baseUrl, "/api/servers", {
    method: "POST",
    body: JSON.stringify(data),
  })
  return serverReadSchema.parse(payload)
}

export async function updateServer(baseUrl: string, id: string, data: ServerUpdate): Promise<ServerRead> {
  const payload = await requestJson<unknown>(baseUrl, `/api/servers/${id}`, {
    method: "PUT",
    body: JSON.stringify(data),
  })
  return serverReadSchema.parse(payload)
}

export async function deleteServer(baseUrl: string, id: string): Promise<void> {
  await requestJson<void>(baseUrl, `/api/servers/${id}`, { method: "DELETE" })
}

export async function pollServer(baseUrl: string, id: string): Promise<void> {
  await requestJson<unknown>(baseUrl, `/api/servers/${id}/poll`, { method: "POST" })
}

export async function testServerConnection(
  baseUrl: string,
  payload: TestConnectionRequest,
): Promise<TestConnectionResponse> {
  testConnectionSchema.parse(payload)
  return requestJson<TestConnectionResponse>(baseUrl, "/api/servers/test-connection", {
    method: "POST",
    body: JSON.stringify(payload),
  })
}
