import { beforeEach, describe, expect, it } from 'vitest';
import { handleActuateAPI } from '../../api/index.js';
import { initDB } from '../../db.js';
function createMockDB(docs) {
    const rows = docs.map((d) => ({ ...d, deletedAt: d.deletedAt ?? null }));
    const matches = (d, where) => {
        if (!where)
            return true;
        if (where.id && d.id !== where.id)
            return false;
        if (where.collection && d.collection !== where.collection)
            return false;
        if (where.status && d.status !== where.status)
            return false;
        if (where.deletedAt === null && d.deletedAt)
            return false;
        if (where.OR && Array.isArray(where.OR)) {
            return where.OR.some((clause) => {
                if (clause.slug !== undefined)
                    return d.slug === clause.slug;
                if (clause.data?.path && clause.data?.equals !== undefined) {
                    return d.data?.[clause.data.path[0]] === clause.data.equals;
                }
                return false;
            });
        }
        return true;
    };
    return {
        apiKey: { findMany: async () => [], findUnique: async () => null },
        document: {
            findMany: async ({ where } = {}) => rows.filter((d) => matches(d, where)),
            findFirst: async ({ where }) => rows.find((d) => matches(d, where ?? {})) ?? null,
            count: async () => rows.length,
        },
        version: { create: async () => ({}), findMany: async () => [], count: async () => 0 },
        auditLog: { create: async () => ({}) },
        webhook: { findMany: async () => [] },
        webhookDelivery: { create: async () => ({}) },
        user: {},
        session: {},
        media: {},
    };
}
const pagesCollection = {
    slug: 'pages',
    labels: { singular: 'Page', plural: 'Pages' },
    type: 'page',
    urlPrefix: '',
    fields: {
        title: { type: 'text', label: 'Title', required: true },
        slug: { type: 'slug', label: 'Slug', required: true },
        sections: { type: 'json', label: 'Sections' },
    },
};
const cmsConfig = { collections: { pages: pagesCollection } };
// A page-builder tree (page → section → row → column → hero block) with no
// flat `sections` array of its own.
const layoutTree = {
    id: 'page',
    type: 'page',
    children: [
        {
            id: 'sec',
            type: 'section',
            settings: { htmlId: 'top' },
            children: [
                {
                    id: 'row',
                    type: 'row',
                    settings: {},
                    children: [
                        {
                            id: 'col',
                            type: 'column',
                            settings: { width: 12 },
                            children: [
                                {
                                    id: 'blk',
                                    type: 'block',
                                    settings: { blockType: 'hero' },
                                    data: { title: 'Welcome home', subtitle: 'Built in the page builder' },
                                },
                            ],
                        },
                    ],
                },
            ],
        },
    ],
};
beforeEach(() => {
    delete globalThis.__actuateConfig;
    process.env.CMS_SECRET = 'a'.repeat(48);
});
describe('GET /resolve — page-builder (_layout) → sections bridge', () => {
    it('derives data.sections from _layout when the page has no flat sections', async () => {
        const docs = [
            {
                id: 'doc-1',
                collection: 'pages',
                slug: 'home',
                status: 'PUBLISHED',
                data: { title: 'Home', slug: 'home', _layout: layoutTree },
                publishedAt: new Date('2026-01-01T00:00:00Z'),
                updatedAt: new Date('2026-01-01T00:00:00Z'),
            },
        ];
        const db = createMockDB(docs);
        initDB(db);
        const handler = handleActuateAPI({ prismaClient: db, config: cmsConfig });
        const res = await handler(new Request('https://example.com/api/cms/resolve?path=/home'));
        expect(res.status).toBe(200);
        const body = await res.json();
        const sections = body.data.data.sections;
        expect(Array.isArray(sections)).toBe(true);
        expect(sections).toHaveLength(1);
        expect(sections[0].sectionType).toBe('hero');
        expect(sections[0].content).toMatchObject({
            heading: 'Welcome home',
            body: 'Built in the page builder',
        });
        expect(sections[0].settings.anchorId).toBe('top');
        // The raw tree is never exposed to the client.
        expect(body.data.data._layout).toBeUndefined();
    });
    it('does not overwrite an existing flat sections array', async () => {
        const docs = [
            {
                id: 'doc-2',
                collection: 'pages',
                slug: 'about',
                status: 'PUBLISHED',
                data: {
                    title: 'About',
                    slug: 'about',
                    _layout: layoutTree,
                    sections: [
                        {
                            id: 's1',
                            sectionType: 'text',
                            name: 'Text Block',
                            visible: true,
                            content: { heading: 'Hand-authored', body: 'wins' },
                            settings: {},
                        },
                    ],
                },
                publishedAt: new Date('2026-01-01T00:00:00Z'),
                updatedAt: new Date('2026-01-01T00:00:00Z'),
            },
        ];
        const db = createMockDB(docs);
        initDB(db);
        const handler = handleActuateAPI({ prismaClient: db, config: cmsConfig });
        const res = await handler(new Request('https://example.com/api/cms/resolve?path=/about'));
        expect(res.status).toBe(200);
        const body = await res.json();
        const sections = body.data.data.sections;
        expect(sections).toHaveLength(1);
        expect(sections[0].sectionType).toBe('text');
        expect(sections[0].content.heading).toBe('Hand-authored');
    });
});
//# sourceMappingURL=resolve-layout-bridge.test.js.map