/**
 * Forms service — typed client over the cms-core Forms REST endpoints.
 *
 * Every Forms admin component reads/writes through this module (never raw
 * `cmsApi` / `fetch`), so the network contract lives in one place. Read
 * fetchers re-surface `cmsApi`'s `{ error }` as a thrown error (so the
 * resource hook can show error/retry UI); mutations return `{ error? }`.
 *
 * The endpoint paths here are the contract implemented by cms-core
 * `packages/cms-core/src/api/handlers.ts` (PR 2). Domain types are re-used
 * from `@actuate-media/cms-core` so the admin can never drift from the server.
 */
import { cmsApi } from './api.js';
/**
 * `cmsApi` never throws — it returns `{ error, status }` on a network/HTTP
 * failure. Read (GET) fetchers must re-surface that as a thrown error so the
 * resource hook can distinguish "request failed" from "empty result".
 */
function throwIfError(res) {
    if (res.error)
        throw new Error(res.error);
}
// ─── Forms list / stats / sidebar ────────────────────────────────────────
function buildFormsQuery(params) {
    const qs = new URLSearchParams();
    if (params.search)
        qs.set('search', params.search);
    if (params.status)
        qs.set('status', params.status);
    if (typeof params.notifyEnabled === 'boolean') {
        qs.set('notifyEnabled', String(params.notifyEnabled));
    }
    if (params.sortBy)
        qs.set('sortBy', params.sortBy);
    if (params.sortDirection)
        qs.set('sortDirection', params.sortDirection);
    if (params.page)
        qs.set('page', String(params.page));
    if (params.pageSize)
        qs.set('pageSize', String(params.pageSize));
    const str = qs.toString();
    return str ? `?${str}` : '';
}
export async function fetchForms(params = {}) {
    const res = await cmsApi(`/forms${buildFormsQuery(params)}`);
    throwIfError(res);
    return res.data ?? [];
}
export async function fetchFormById(id) {
    const res = await cmsApi(`/forms/${encodeURIComponent(id)}`);
    throwIfError(res);
    return res.data ?? null;
}
const EMPTY_STATS = {
    totalForms: 0,
    activeForms: 0,
    totalEntries: 0,
    unreadEntries: 0,
};
export async function fetchFormStats() {
    const res = await cmsApi('/forms/stats');
    throwIfError(res);
    return res.data ?? EMPTY_STATS;
}
export async function fetchFormsSidebarCounts() {
    const res = await cmsApi('/forms/sidebar-counts');
    throwIfError(res);
    return res.data ?? [];
}
export async function createForm(payload) {
    const res = await cmsApi('/forms', {
        method: 'POST',
        body: JSON.stringify(payload),
    });
    return { data: res.data, error: res.error };
}
export async function updateForm(id, payload) {
    const res = await cmsApi(`/forms/${encodeURIComponent(id)}`, {
        method: 'PATCH',
        body: JSON.stringify(payload),
    });
    return { data: res.data, error: res.error };
}
export async function duplicateForm(id) {
    const res = await cmsApi(`/forms/${encodeURIComponent(id)}/duplicate`, {
        method: 'POST',
    });
    return { data: res.data, error: res.error };
}
/** Move a form to the archived state (hidden from embed pickers, no new submissions). */
export async function archiveForm(id) {
    return updateForm(id, { status: 'archived' });
}
/** Restore an archived form back to draft. */
export async function restoreForm(id) {
    return updateForm(id, { status: 'draft' });
}
export async function deleteForm(id, opts = {}) {
    const qs = opts.force ? '?force=true' : '';
    const res = await cmsApi(`/forms/${encodeURIComponent(id)}${qs}`, { method: 'DELETE' });
    return { error: res.error };
}
// ─── Schema ──────────────────────────────────────────────────────────────
export async function fetchFormSchema(id) {
    const res = await cmsApi(`/forms/${encodeURIComponent(id)}/schema`);
    throwIfError(res);
    return res.data ?? { fields: [], activeVersionId: null, versions: [] };
}
export async function saveFormSchema(id, fields, notes) {
    const res = await cmsApi(`/forms/${encodeURIComponent(id)}/schema`, { method: 'PUT', body: JSON.stringify({ fields, notes }) });
    return { data: res.data, error: res.error };
}
// ─── Notifications ─────────────────────────────────────────────────────────
export async function fetchNotificationSettings(id) {
    const res = await cmsApi(`/forms/${encodeURIComponent(id)}/notifications`);
    throwIfError(res);
    return res.data ?? { enabled: false, recipients: [] };
}
export async function updateNotificationSettings(id, payload) {
    const res = await cmsApi(`/forms/${encodeURIComponent(id)}/notifications`, { method: 'PUT', body: JSON.stringify(payload) });
    return { data: res.data, error: res.error };
}
/** Lightweight notify on/off toggle used by the forms-list switch. */
export async function setNotifyEnabled(id, enabled) {
    const res = await cmsApi(`/forms/${encodeURIComponent(id)}/notify`, {
        method: 'PUT',
        body: JSON.stringify({ enabled }),
    });
    return { data: res.data, error: res.error };
}
// ─── Embed ───────────────────────────────────────────────────────────────
export async function fetchEmbedSettings(id) {
    const res = await cmsApi(`/forms/${encodeURIComponent(id)}/embed`);
    throwIfError(res);
    return res.data ?? {};
}
export async function updateEmbedSettings(id, payload) {
    const res = await cmsApi(`/forms/${encodeURIComponent(id)}/embed`, {
        method: 'PUT',
        body: JSON.stringify(payload),
    });
    return { data: res.data, error: res.error };
}
function buildEntriesQuery(params) {
    const qs = new URLSearchParams();
    if (params.search)
        qs.set('search', params.search);
    if (params.formId)
        qs.set('formId', params.formId);
    if (typeof params.unread === 'boolean')
        qs.set('unread', String(params.unread));
    if (typeof params.starred === 'boolean')
        qs.set('starred', String(params.starred));
    if (typeof params.archived === 'boolean')
        qs.set('archived', String(params.archived));
    if (params.spamStatus)
        qs.set('spamStatus', params.spamStatus);
    if (params.dateFrom)
        qs.set('dateFrom', params.dateFrom);
    if (params.dateTo)
        qs.set('dateTo', params.dateTo);
    if (params.thisWeek)
        qs.set('thisWeek', 'true');
    if (params.sortBy)
        qs.set('sortBy', params.sortBy);
    if (params.sortDirection)
        qs.set('sortDirection', params.sortDirection);
    if (params.page)
        qs.set('page', String(params.page));
    if (params.pageSize)
        qs.set('pageSize', String(params.pageSize));
    const str = qs.toString();
    return str ? `?${str}` : '';
}
const EMPTY_PAGE = { entries: [], total: 0, page: 1, pageSize: 25 };
export async function fetchEntries(params = {}) {
    const res = await cmsApi(`/forms/entries${buildEntriesQuery(params)}`);
    throwIfError(res);
    return res.data ?? EMPTY_PAGE;
}
const EMPTY_COUNTS = { total: 0, unread: 0, starred: 0, thisWeek: 0, byForm: {} };
export async function fetchEntryCounts(params = {}) {
    const res = await cmsApi(`/forms/entries/counts${buildEntriesQuery(params)}`);
    throwIfError(res);
    return res.data ?? EMPTY_COUNTS;
}
export async function fetchEntry(id) {
    const res = await cmsApi(`/forms/entries/${encodeURIComponent(id)}`);
    throwIfError(res);
    return res.data ?? null;
}
export async function updateEntry(id, patch) {
    const res = await cmsApi(`/forms/entries/${encodeURIComponent(id)}`, {
        method: 'PATCH',
        body: JSON.stringify(patch),
    });
    return { data: res.data, error: res.error };
}
export async function deleteEntry(id) {
    const res = await cmsApi(`/forms/entries/${encodeURIComponent(id)}`, { method: 'DELETE' });
    return { error: res.error };
}
export async function bulkUpdateEntries(ids, patch) {
    const res = await cmsApi('/forms/entries/bulk', {
        method: 'POST',
        body: JSON.stringify({ ids, patch }),
    });
    return { data: res.data, error: res.error };
}
//# sourceMappingURL=forms-service.js.map