import type {
  AnalyzeResponse,
  CompileResponse,
  LayoutActionResponse,
  SchemetaRequest
} from "./types";

async function postJson<TResponse>(path: string, body: unknown): Promise<TResponse> {
  const response = await fetch(path, {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(body)
  });

  const data = (await response.json()) as TResponse & {
    error?: { message?: string };
    message?: string;
  };

  if (!response.ok) {
    const message = data?.error?.message ?? data?.message ?? `Request failed with status ${response.status}`;
    throw new Error(message);
  }

  return data;
}

export function compile(payload: unknown, options: Record<string, unknown> = {}): Promise<CompileResponse> {
  const body: SchemetaRequest = { payload, options };
  return postJson<CompileResponse>("/compile", body);
}

export function analyze(payload: unknown, options: Record<string, unknown> = {}): Promise<AnalyzeResponse> {
  const body: SchemetaRequest = { payload, options };
  return postJson<AnalyzeResponse>("/analyze", body);
}

export function autoLayout(payload: unknown, options: Record<string, unknown> = {}): Promise<LayoutActionResponse> {
  const body: SchemetaRequest = { payload, options };
  return postJson<LayoutActionResponse>("/layout/auto", body);
}

export function tidyLayout(payload: unknown, options: Record<string, unknown> = {}): Promise<LayoutActionResponse> {
  const body: SchemetaRequest = { payload, options };
  return postJson<LayoutActionResponse>("/layout/tidy", body);
}
