import { beforeEach, describe, expect, it } from 'vitest';
import { handleActuateAPI } from '../../api/index.js';
import { createSession } from '../../auth/session.js';
import { initDB } from '../../db.js';
const SECRET = 'test-secret-for-admin-contracts-1234567890';
async function authHeaders() {
    const token = await createSession({ userId: 'admin-1', role: 'ADMIN', sessionId: 'session-1' }, { secret: SECRET });
    return { cookie: `actuate_session=${token}` };
}
function createMockDB() {
    return {
        session: {
            findUnique: async () => ({ revokedAt: null }),
        },
        user: {},
        media: {
            findMany: async () => [
                {
                    id: 'media-1',
                    filename: 'hero.jpg',
                    mimeType: 'image/jpeg',
                    fileSize: 2048,
                    storageKey: 'uploads/hero.jpg',
                    altText: 'Hero image',
                    title: 'Hero',
                    width: 1200,
                    height: 800,
                    createdAt: new Date('2026-01-01T00:00:00.000Z'),
                    updatedAt: new Date('2026-01-02T00:00:00.000Z'),
                },
            ],
            count: async () => 1,
        },
        document: {
            findMany: async (args) => {
                if (args?.where?.collection === 'forms') {
                    return [
                        {
                            id: 'form-1',
                            title: 'Legacy Title',
                            data: {
                                name: 'Contact Form',
                                description: 'Contact us',
                                fields: [{ name: 'email' }, { name: 'message' }],
                            },
                            createdAt: new Date('2026-01-03T00:00:00.000Z'),
                            updatedAt: new Date('2026-01-04T00:00:00.000Z'),
                        },
                    ];
                }
                return [
                    {
                        id: 'page-1',
                        collection: 'pages',
                        title: 'Home',
                        slug: 'home',
                        data: {
                            title: 'Home',
                            slug: 'home',
                            metaTitle: 'Home Meta',
                            metaDescription: 'Home description',
                            canonical: 'https://example.com/',
                            schemaType: 'WebPage',
                        },
                        structuredData: { score: 82, issues: ['missing-og'] },
                        updatedAt: new Date('2026-01-05T00:00:00.000Z'),
                    },
                ];
            },
        },
        formSubmission: {
            findMany: async () => [
                {
                    id: 'submission-1',
                    data: { name: 'Ada', email: 'ada@example.com', message: 'Hello' },
                    attribution: { source: 'google', medium: 'cpc' },
                    status: 'new',
                    submittedAt: new Date('2026-01-06T00:00:00.000Z'),
                },
            ],
            count: async () => 1,
            groupBy: async () => [{ formId: 'form-1', _count: { _all: 1 } }],
        },
        redirect: {
            findMany: async () => [
                {
                    id: 'redirect-1',
                    source: '/old',
                    destination: '/new',
                    statusCode: 301,
                    createdAt: new Date('2026-01-07T00:00:00.000Z'),
                    updatedAt: new Date('2026-01-08T00:00:00.000Z'),
                },
            ],
        },
    };
}
describe('admin API response contracts', () => {
    beforeEach(() => {
        process.env.CMS_SECRET = SECRET;
        const db = createMockDB();
        initDB(db);
    });
    it('normalizes media list items to the shape consumed by cms-admin', async () => {
        const handler = handleActuateAPI({ prismaClient: createMockDB() });
        const response = await handler(new Request('https://example.com/api/cms/media', {
            headers: await authHeaders(),
        }));
        await expect(response.json()).resolves.toMatchObject({
            data: {
                data: [
                    {
                        id: 'media-1',
                        name: 'hero.jpg',
                        type: 'image/jpeg',
                        size: '2.0 KB',
                        sizeBytes: 2048,
                        url: '',
                        altTag: 'Hero image',
                        title: 'Hero',
                        dimensions: '1200x800',
                    },
                ],
                total: 1,
            },
        });
    });
    it('normalizes forms, submissions, redirects, and SEO pages for cms-admin', async () => {
        const handler = handleActuateAPI({ prismaClient: createMockDB() });
        const headers = await authHeaders();
        const [forms, submissions, redirects, seoPages] = await Promise.all([
            handler(new Request('https://example.com/api/cms/forms', { headers })),
            handler(new Request('https://example.com/api/cms/forms/form-1/submissions', { headers })),
            handler(new Request('https://example.com/api/cms/redirects', { headers })),
            handler(new Request('https://example.com/api/cms/seo/pages', { headers })),
        ]);
        // `fields` is now the typed field array; `fieldCount` is the legacy count
        // alias and `submissions` mirrors `totalEntries` for older admin views.
        const formsBody = (await forms.json());
        expect(formsBody.data[0]).toMatchObject({
            id: 'form-1',
            name: 'Contact Form',
            fieldCount: 2,
            submissions: 1,
        });
        expect(Array.isArray(formsBody.data[0].fields)).toBe(true);
        expect(formsBody.data[0].fields.length).toBe(2);
        await expect(submissions.json()).resolves.toMatchObject({
            data: {
                submissions: [
                    {
                        id: 'submission-1',
                        name: 'Ada',
                        email: 'ada@example.com',
                        message: 'Hello',
                        status: 'new',
                        attribution: { source: 'google', medium: 'cpc' },
                    },
                ],
                total: 1,
            },
        });
        await expect(redirects.json()).resolves.toMatchObject({
            data: [{ id: 'redirect-1', from: '/old', to: '/new', type: '301' }],
        });
        await expect(seoPages.json()).resolves.toMatchObject({
            data: [
                {
                    id: 'page-1',
                    url: '/',
                    title: 'Home',
                    score: 82,
                    issues: 1,
                    metaTitle: 'Home Meta',
                    metaDescription: 'Home description',
                },
            ],
        });
    });
});
//# sourceMappingURL=admin-contracts.test.js.map