import { beforeEach, describe, expect, it } from 'vitest';
import { handleActuateAPI } from '../../api/index.js';
import { initDB } from '../../db.js';
import { generateApiKey } from '../../security/api-key-enhanced.js';
/**
 * Authenticated `GET /globals/:slug` behaviour.
 *
 * Globals are upsert-on-write (the first PUT creates the row). A slug that has
 * no document yet is therefore a valid EMPTY state, not a 404 — the shipped
 * admin Settings page reads `/globals/settings` and must load cleanly on a
 * fresh install before anything has been saved. This regression test pins
 * that contract so we don't reintroduce the "Global not found" banner.
 */
const VALID_SECRET = 'a'.repeat(48);
function createMockDB(opts) {
    const apiKey = opts.apiKey;
    return {
        apiKey: {
            findMany: async () => (apiKey ? [apiKey] : []),
            findUnique: async ({ where }) => {
                if (!apiKey)
                    return null;
                if (apiKey.keyHash !== where.keyHash)
                    return null;
                return apiKey;
            },
            update: async () => apiKey,
        },
        document: {
            findFirst: async () => opts.global ?? null,
            findMany: async () => [],
            count: async () => 0,
        },
        user: {},
        session: {},
        media: {},
    };
}
async function makeKey(scopes) {
    const { key, keyHash, keyPrefix } = await generateApiKey({ prefix: 'act_sk', scopes });
    return {
        key,
        record: {
            id: 'apikey-1',
            keyHash,
            keyPrefix,
            userId: 'user-1',
            scopes,
            ipRestrictions: null,
            expiresAt: null,
            lastUsedAt: null,
            revokedAt: null,
        },
    };
}
function makeHandler(db) {
    return handleActuateAPI({ prismaClient: db, config: { collections: {} } });
}
describe('GET /globals/:slug (authenticated)', () => {
    beforeEach(() => {
        delete globalThis.__actuateConfig;
        process.env.CMS_SECRET = VALID_SECRET;
    });
    it('returns 200 with empty data when the global has never been saved', async () => {
        const { key, record } = await makeKey({ globals: ['settings'] });
        const db = createMockDB({ apiKey: record, global: null });
        initDB(db);
        const handler = makeHandler(db);
        const response = await handler(new Request('https://example.com/api/cms/globals/settings', {
            headers: { Authorization: `Bearer ${key}` },
        }));
        expect(response.status).toBe(200);
        await expect(response.json()).resolves.toEqual({ data: {} });
    });
    it('returns the stored data when the global document exists', async () => {
        const { key, record } = await makeKey({ globals: ['settings'] });
        const db = createMockDB({
            apiKey: record,
            global: { id: 'doc-1', collection: 'settings', data: { siteTitle: 'Actuate Media' } },
        });
        initDB(db);
        const handler = makeHandler(db);
        const response = await handler(new Request('https://example.com/api/cms/globals/settings', {
            headers: { Authorization: `Bearer ${key}` },
        }));
        expect(response.status).toBe(200);
        await expect(response.json()).resolves.toEqual({ data: { siteTitle: 'Actuate Media' } });
    });
    it('rejects with 403 when the API key is not scoped to the global', async () => {
        const { key, record } = await makeKey({ collections: ['posts'], actions: ['read'] });
        const db = createMockDB({ apiKey: record, global: null });
        initDB(db);
        const handler = makeHandler(db);
        const response = await handler(new Request('https://example.com/api/cms/globals/settings', {
            headers: { Authorization: `Bearer ${key}` },
        }));
        expect(response.status).toBe(403);
    });
});
//# sourceMappingURL=globals-routes.test.js.map