import { updateDocumentSeoFields } from '../actions.js';
import { getActuateConfig } from '../config/runtime.js';
import { applySeoOverrides, getSeoOverrides } from './config-store.js';
import { frontEndContentCollectionTypes } from './audit-runner.js';
import { isPublicContentCollection } from './schema-sync.js';
import { resolveEffectiveMeta } from './page-meta.js';
function isPlainObject(v) {
    return !!v && typeof v === 'object' && !Array.isArray(v);
}
function pickString(...candidates) {
    for (const c of candidates) {
        if (typeof c === 'string' && c.trim().length > 0)
            return c.trim();
    }
    return undefined;
}
function needsMetaMigration(data) {
    return (!pickString(data.metaTitle, data.seoTitle) ||
        !pickString(data.metaDescription, data.seoDescription));
}
/** Backfill metaTitle/metaDescription from effective render-time values. */
export async function migrateMetaFields(ctx, options = {}) {
    const dryRun = options.dryRun ?? false;
    const batchSize = options.batchSize && options.batchSize > 0 ? options.batchSize : 100;
    const config = getActuateConfig();
    const defaultCollections = Object.keys(frontEndContentCollectionTypes(config));
    const targetCollections = options.collections && options.collections.length > 0 ? options.collections : defaultCollections;
    const result = {
        scanned: 0,
        migrated: 0,
        skipped: 0,
        migratedIds: [],
    };
    if (targetCollections.length === 0)
        return result;
    const overrides = await getSeoOverrides(ctx.db).catch(() => null);
    const mergedConfig = applySeoOverrides(config, overrides);
    const siteSeo = mergedConfig?.seo;
    const siteUrl = siteSeo?.siteUrl?.replace(/\/+$/, '');
    // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Prisma client is intentionally untyped at the core/config boundary.
    const db = ctx.db;
    let cursor;
    for (;;) {
        const batch = await db.document.findMany({
            where: {
                deletedAt: null,
                status: 'PUBLISHED',
                collection: { in: targetCollections },
            },
            orderBy: { id: 'asc' },
            take: batchSize,
            ...(cursor ? { skip: 1, cursor: { id: cursor } } : {}),
            select: {
                id: true,
                collection: true,
                title: true,
                slug: true,
                status: true,
                data: true,
                publishedAt: true,
            },
        });
        if (batch.length === 0)
            break;
        cursor = batch[batch.length - 1].id;
        for (const doc of batch) {
            result.scanned++;
            const data = isPlainObject(doc.data) ? doc.data : null;
            if (!data) {
                result.skipped++;
                continue;
            }
            const collectionDef = mergedConfig?.collections?.[doc.collection] ?? null;
            if (!isPublicContentCollection(collectionDef)) {
                result.skipped++;
                continue;
            }
            if (!needsMetaMigration(data)) {
                result.skipped++;
                continue;
            }
            const effective = resolveEffectiveMeta({
                data,
                docTitle: doc.title,
                publishedAt: doc.publishedAt,
                collection: collectionDef,
                collectionSlug: doc.collection,
                site: siteSeo,
                siteUrl,
            });
            const patch = {};
            if (!pickString(data.metaTitle, data.seoTitle) && effective.metaTitle) {
                patch.metaTitle = effective.metaTitle;
            }
            if (!pickString(data.metaDescription, data.seoDescription) && effective.metaDescription) {
                patch.metaDescription = effective.metaDescription;
            }
            if (Object.keys(patch).length === 0) {
                result.skipped++;
                continue;
            }
            if (!dryRun) {
                await updateDocumentSeoFields(doc.collection, doc.id, patch, ctx);
            }
            result.migrated++;
            result.migratedIds.push(doc.id);
        }
        if (batch.length < batchSize)
            break;
    }
    return result;
}
//# sourceMappingURL=migrate-meta.js.map