/**
 * API helper wrapping @wordpress/api-fetch for Mintall REST endpoints.
 */
import apiFetch from '@wordpress/api-fetch';
import { setReauthRequired } from './reauth';

// Configure the middleware for our nonce.
apiFetch.use(apiFetch.createNonceMiddleware(window.mintallKeep?.nonce));
apiFetch.use(
	apiFetch.createRootURLMiddleware(window.mintallKeep?.apiBase?.replace(/\/mintall\/v1$/, '/') || '/wp-json/'),
);

// Trip the reauth banner whenever a call fails with REAUTH_REQUIRED, so any page
// (e.g. a failed protect on Products) raises it without its own handling.
// Re-throw so callers still see the error.
apiFetch.use((options, next) =>
	(next(options) as Promise<unknown>).catch((err: unknown) => {
		if (err && typeof err === 'object' && (err as { error?: string }).error === 'REAUTH_REQUIRED') {
			setReauthRequired(true);
		}
		throw err;
	}),
);

const BASE = 'mintall/v1';

export const api = {
	get: <T = unknown>(path: string, params: Record<string, string | number> = {}): Promise<T> => {
		const entries: Record<string, string> = {};
		for (const [k, v] of Object.entries(params)) {
			entries[k] = String(v);
		}
		const query = new URLSearchParams(entries).toString();
		const url = query ? `${BASE}${path}?${query}` : `${BASE}${path}`;
		return apiFetch({ path: url }) as Promise<T>;
	},

	post: <T = unknown>(path: string, data: Record<string, unknown> = {}): Promise<T> =>
		apiFetch({
			path: `${BASE}${path}`,
			method: 'POST',
			data,
		}) as Promise<T>,

	del: <T = unknown>(path: string, data?: Record<string, unknown>): Promise<T> =>
		apiFetch({
			path: `${BASE}${path}`,
			method: 'DELETE',
			...(data ? { data } : {}),
		}) as Promise<T>,
};
