import apiFetch from "@wordpress/api-fetch";
import type { APIFetchOptions } from "@wordpress/api-fetch";
import { adminConfig } from "../config";

const restBase = adminConfig.restBase;

export const apiErrorStatus = (error: unknown): number | undefined => {
  if (typeof error !== "object" || error === null || !("data" in error)) return undefined;

  const data = error.data;
  if (typeof data !== "object" || data === null || !("status" in data)) return undefined;

  return typeof data.status === "number" ? data.status : undefined;
};

export const apiErrorCode = (error: unknown): string | undefined =>
  typeof error === "object" && error !== null && "code" in error && typeof error.code === "string"
    ? error.code
    : undefined;

export const apiErrorMessage = (error: unknown): string | undefined => {
  if (typeof error === "object" && error !== null && "message" in error) {
    const msg = error.message;
    if (typeof msg === "string" && msg.trim().length > 0) return msg;
  }
  if (error instanceof Error && error.message) return error.message;

  return undefined;
};

export function wpGet<TResponse>(path: string): Promise<TResponse> {
  return apiFetch<TResponse>({ path: `${restBase}${path}` });
}

export function wpPost<TResponse, TData extends object = Record<string, never>>(
  path: string,
  data?: TData,
): Promise<TResponse> {
  const options: APIFetchOptions<true> = {
    path: `${restBase}${path}`,
    method: "POST",
  };

  if (data) {
    options.data = data;
  }

  return apiFetch<TResponse>(options);
}

export function wpDelete<TResponse>(path: string): Promise<TResponse> {
  return apiFetch<TResponse>({
    path: `${restBase}${path}`,
    method: "DELETE",
  });
}
