// @File: src/lib/uptimerobotMcpApi.ts
// @Desc: Admin-side fetch wrappers for the UptimeRobot MCP integration
//        (endpoint config + connectivity probe). Auth mirrors the rest of
//        the admin surface: JWT from localStorage.
import { getToken } from "@/lib/auth";

function authHeaders(): HeadersInit {
  const token = getToken();
  return {
    "Content-Type": "application/json",
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
  };
}

async function handle<T>(res: Response): Promise<T> {
  const raw = await res.text();
  let data: unknown = null;
  if (raw) {
    try {
      data = JSON.parse(raw);
    } catch {
      data = raw;
    }
  }
  if (!res.ok) {
    const detail =
      (data && typeof data === "object" && "detail" in (data as Record<string, unknown>)
        ? String((data as Record<string, unknown>).detail)
        : null) ||
      res.statusText ||
      "Request failed";
    throw new Error(detail);
  }
  return data as T;
}

export interface UptimeMcpCapability {
  id: string;
  title: string;
  description: string;
}

export interface UptimeMcpConfig {
  endpoint: string;
  auth_scheme: string;
  static_headers: Record<string, string>;
  api_key_present: boolean;
  api_key_masked: string | null;
  api_key_source: "db" | "env" | "none" | string;
  config_json: string;
  capabilities: UptimeMcpCapability[];
  sample_prompts: string[];
  doc_url: string;
}

export interface UptimeMcpProbeResult {
  ok: boolean;
  http_status: number | null;
  error_class?: string;
  error_message?: string;
  api_key_source?: string;
  endpoint?: string;
  detail?: string;
}

const BASE = "/api/v1/admin/uptimerobot/mcp";

export async function urAdminGetMcpConfig(): Promise<UptimeMcpConfig> {
  const res = await fetch(`${BASE}/config`, { headers: authHeaders() });
  return handle<UptimeMcpConfig>(res);
}

export async function urAdminTestMcpEndpoint(): Promise<UptimeMcpProbeResult> {
  const res = await fetch(`${BASE}/test`, {
    method: "POST",
    headers: authHeaders(),
  });
  return handle<UptimeMcpProbeResult>(res);
}