/**
 * Structured-data defaults for content documents.
 *
 * Public pages already emit JSON-LD via `composePageMeta()` at render time, but
 * the SEO audit and Content SEO list read persisted `structuredDataType` on the
 * document. This module keeps those in sync with the same resolution order the
 * page build / `/resolve` path uses.
 */
import { composePageMeta, detectSchemaType } from './page-meta.js';
function pickString(...candidates) {
    for (const c of candidates) {
        if (typeof c === 'string' && c.trim().length > 0)
            return c.trim();
    }
    return undefined;
}
function asRecord(v) {
    return v && typeof v === 'object' && !Array.isArray(v) ? v : null;
}
/** Extract a primary Schema.org type from stored JSON-LD. */
function schemaTypeFromStructuredData(structured) {
    if (!structured)
        return undefined;
    const direct = structured['@type'];
    if (typeof direct === 'string' && direct.trim())
        return direct.trim();
    const graph = structured['@graph'];
    if (!Array.isArray(graph))
        return undefined;
    const skip = new Set(['WebSite', 'Organization', 'BreadcrumbList', 'ImageObject']);
    for (const node of graph) {
        const rec = asRecord(node);
        const type = rec?.['@type'];
        if (typeof type === 'string' && !skip.has(type))
            return type;
        if (Array.isArray(type)) {
            const primary = type.find((t) => typeof t === 'string' && !skip.has(t));
            if (typeof primary === 'string')
                return primary;
        }
    }
    return undefined;
}
function pageSettingsFromData(data) {
    const ps = data._pageSettings ?? data.pageSettings;
    return asRecord(ps) ?? undefined;
}
/** True when the collection renders a public page or post. */
export function isPublicContentCollection(collectionDef) {
    return collectionDef?.type === 'page' || collectionDef?.type === 'post';
}
/**
 * Resolve the Schema.org type a document will emit — same precedence as
 * `composePageMeta()`.
 */
export function resolveEffectiveSchemaType(params) {
    const data = params.data ?? {};
    const pageSettings = pageSettingsFromData(data);
    const fromColumn = schemaTypeFromStructuredData(asRecord(params.structuredData));
    if (fromColumn)
        return fromColumn;
    return (pickString(data.structuredDataType, data.schemaType, pageSettings?.schemaType, pageSettings?.structuredDataType, params.collectionDef?.seo?.defaultSchemaType) ?? detectSchemaType(params.collection));
}
/** Keep `structuredDataType` and `schemaType` in sync when either is set. */
export function syncSchemaTypeFields(fields) {
    const type = pickString(fields.structuredDataType, fields.schemaType);
    if (!type)
        return fields;
    return { ...fields, structuredDataType: type, schemaType: type };
}
/** Stamp `structuredDataType` / `schemaType` on document data when unset. */
export function applyStructuredDataFieldsToData(collection, data, collectionDef, structuredData) {
    const effective = resolveEffectiveSchemaType({
        collection,
        data,
        structuredData,
        collectionDef,
    });
    const next = { ...data };
    if (!pickString(data.structuredDataType))
        next.structuredDataType = effective;
    if (!pickString(data.schemaType))
        next.schemaType = effective;
    return next;
}
/**
 * Compose JSON-LD for a published document when the `structuredData` column is
 * empty. Respects explicit overrides already stored on the column.
 */
export function composeStructuredDataForPublish(params) {
    const existing = asRecord(params.doc.structuredData);
    if (existing && Object.keys(existing).length > 0)
        return existing;
    const collectionDef = params.config?.collections?.[params.collection] ?? null;
    const pageSettings = pageSettingsFromData(params.doc.data);
    const composed = composePageMeta({
        doc: {
            id: params.doc.id,
            collection: params.collection,
            slug: params.doc.slug,
            data: params.doc.data,
            publishedAt: params.doc.publishedAt,
            updatedAt: params.doc.updatedAt,
            structuredData: null,
            pageSettings: pageSettings ?? null,
        },
        collection: collectionDef,
        config: params.config,
    });
    return composed.jsonLd ?? null;
}
/**
 * Apply structured-data defaults on content document writes. When publishing,
 * also materialize JSON-LD on the document column for audits/API consumers.
 */
export function prepareContentStructuredData(collection, data, options = {}) {
    const { collectionDef, config, existingStructuredData, doc, publishing } = options;
    if (!isPublicContentCollection(collectionDef)) {
        return { data };
    }
    const nextData = applyStructuredDataFieldsToData(collection, data, collectionDef, existingStructuredData);
    if (!publishing || !doc?.id) {
        return { data: nextData };
    }
    const structuredData = composeStructuredDataForPublish({
        collection,
        doc: {
            id: doc.id,
            slug: doc.slug,
            data: nextData,
            publishedAt: doc.publishedAt,
            updatedAt: doc.updatedAt,
            structuredData: existingStructuredData,
        },
        config: config ?? null,
    });
    return structuredData ? { data: nextData, structuredData } : { data: nextData };
}
//# sourceMappingURL=schema-sync.js.map