/**
 * Listmonk API proxy helper — reads per-space credentials from module settings
 * and forwards requests with Basic Auth.
 */

import { loadCommunity, getDocumentData } from "../../../server/community-store";

export interface ListmonkConfig {
	url: string;
	user: string;
	password: string;
}

/** Read Listmonk credentials from the space's module settings. */
export async function getListmonkConfig(spaceSlug: string): Promise<ListmonkConfig | null> {
	await loadCommunity(spaceSlug);
	const data = getDocumentData(spaceSlug);
	if (!data) return null;

	const settings = data.meta.moduleSettings?.rsocials;
	if (!settings) return null;

	const url = settings.listmonkUrl as string | undefined;
	const user = settings.listmonkUser as string | undefined;
	const password = settings.listmonkPassword as string | undefined;

	if (!url || !user || !password) return null;
	return { url: url.replace(/\/+$/, ''), user, password };
}

/** Start a Listmonk campaign (set status to "running"). */
export async function startListmonkCampaign(
	config: ListmonkConfig,
	campaignId: number,
): Promise<{ ok: boolean; error?: string }> {
	const res = await listmonkFetch(config, `/api/campaigns/${campaignId}/status`, {
		method: 'PUT',
		body: JSON.stringify({ status: 'running' }),
	});
	if (res.ok) return { ok: true };
	const data = await res.json().catch(() => ({ message: `HTTP ${res.status}` }));
	return { ok: false, error: data.message || `Listmonk returned ${res.status}` };
}

/** Proxy a request to the Listmonk API with Basic Auth. */
export async function listmonkFetch(
	config: ListmonkConfig,
	path: string,
	opts: RequestInit = {},
): Promise<Response> {
	const auth = Buffer.from(`${config.user}:${config.password}`).toString("base64");
	const headers = new Headers(opts.headers);
	headers.set("Authorization", `Basic ${auth}`);
	if (!headers.has("Content-Type") && opts.body) {
		headers.set("Content-Type", "application/json");
	}

	return fetch(`${config.url}${path}`, { ...opts, headers });
}
