import { beforeEach, afterAll, describe, expect, it } from 'vitest';
import { handleActuateAPI } from '../../api/index.js';
import { initDB } from '../../db.js';
const SECRET = 'test-secret-for-public-forms-1234567890';
const FORM_ROW = {
    id: 'form-1',
    title: 'Contact Us',
    slug: 'contact-us',
    collection: 'forms',
    createdById: 'admin-1',
    createdAt: new Date('2026-01-01T00:00:00.000Z'),
    updatedAt: new Date('2026-01-02T00:00:00.000Z'),
    data: {
        name: 'Contact Us',
        slug: 'contact-us',
        status: 'active',
        activeSchemaVersionId: null,
        successMessage: 'Got it!',
        fields: [
            { id: '1', key: 'name', label: 'Name', type: 'text', required: true, sortOrder: 0 },
            { id: '2', key: 'email', label: 'Email', type: 'email', required: true, sortOrder: 1 },
            { id: '3', key: 'hp', label: 'Leave blank', type: 'honeypot', required: false, sortOrder: 2 },
        ],
    },
};
function createMockDB() {
    const created = [];
    const db = {
        created,
        session: { findUnique: async () => ({ revokedAt: null }) },
        user: {},
        media: {},
        document: {
            findFirst: async (args) => {
                const where = args?.where ?? {};
                if (where.collection !== 'forms')
                    return null;
                if (where.slug && where.slug !== 'contact-us')
                    return null;
                if (where.id && where.id !== 'form-1')
                    return null;
                return FORM_ROW;
            },
        },
        formSubmission: {
            aggregate: async () => ({ _max: { entryNumber: 7 } }),
            create: async ({ data }) => {
                created.push(data);
                return { id: 'sub_1', entryNumber: data.entryNumber };
            },
            groupBy: async () => [],
            count: async () => 0,
        },
    };
    db.$transaction = async (fn) => fn(db);
    return db;
}
describe('public form endpoints', () => {
    beforeEach(() => {
        process.env.CMS_SECRET = SECRET;
        process.env.ACTUATE_DISABLE_RATE_LIMIT = '1';
        initDB(createMockDB());
    });
    afterAll(() => {
        delete process.env.ACTUATE_DISABLE_RATE_LIMIT;
    });
    it('serves a public, embeddable schema with the honeypot stripped', async () => {
        const handler = handleActuateAPI({ prismaClient: createMockDB() });
        const res = await handler(new Request('https://example.com/api/cms/public/forms/contact-us', {
            headers: { origin: 'https://embed.site' },
        }));
        expect(res.status).toBe(200);
        expect(res.headers.get('access-control-allow-origin')).toBe('https://embed.site');
        const body = (await res.json());
        expect(body.data.slug).toBe('contact-us');
        expect(body.data.submitPath).toBe('/api/cms/public/forms/contact-us/submit');
        expect(body.data.fields.map((f) => f.key)).toEqual(['name', 'email']);
        expect(body.data.spam.honeypotFieldKey).toBe('hp');
    });
    it('returns 404 for an unknown form', async () => {
        const handler = handleActuateAPI({ prismaClient: createMockDB() });
        const res = await handler(new Request('https://example.com/api/cms/public/forms/missing'));
        expect(res.status).toBe(404);
    });
    it('answers a CORS preflight with 204', async () => {
        const handler = handleActuateAPI({ prismaClient: createMockDB() });
        const res = await handler(new Request('https://example.com/api/cms/public/forms/contact-us/submit', {
            method: 'OPTIONS',
            headers: { origin: 'https://embed.site' },
        }));
        expect(res.status).toBe(204);
        expect(res.headers.get('access-control-allow-methods')).toContain('POST');
    });
    it('accepts a valid JSON submission and returns a confirmation', async () => {
        const db = createMockDB();
        initDB(db);
        const handler = handleActuateAPI({ prismaClient: db });
        const res = await handler(new Request('https://example.com/api/cms/public/forms/contact-us/submit', {
            method: 'POST',
            headers: { 'content-type': 'application/json' },
            body: JSON.stringify({ fields: { name: 'Ada', email: 'ada@calc.io' } }),
        }));
        expect(res.status).toBe(201);
        const body = (await res.json());
        expect(body.data.success).toBe(true);
        expect(body.data.entryNumber).toBe(8);
        expect(body.data.confirmation).toEqual({ type: 'message', message: 'Got it!' });
        expect(db.created[0].senderEmail).toBe('ada@calc.io');
    });
    it('rejects an invalid submission with a 422 and field errors', async () => {
        const db = createMockDB();
        initDB(db);
        const handler = handleActuateAPI({ prismaClient: db });
        const res = await handler(new Request('https://example.com/api/cms/public/forms/contact-us/submit', {
            method: 'POST',
            headers: { 'content-type': 'application/json' },
            body: JSON.stringify({ fields: { name: '', email: 'bad' } }),
        }));
        expect(res.status).toBe(422);
        const body = (await res.json());
        expect(body.code).toBe('VALIDATION_ERROR');
        expect(body.details.length).toBeGreaterThan(0);
    });
});
//# sourceMappingURL=public-forms.test.js.map