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';
/**
 * Regression test for the SEO read-endpoint access blocker. The
 * `/seo/analysis|readability|internal-links|schema|meta` endpoints previously
 * only checked `requireAuth`, so any authenticated principal could pull SEO
 * intelligence for documents in collections they have no read access to. They
 * must now enforce the collection's `access.read` rule.
 */
const VALID_SECRET = 'a'.repeat(48);
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 createMockDB(apiKey, doc) {
    return {
        apiKey: {
            findMany: async () => [apiKey],
            findUnique: async ({ where }) => apiKey.keyHash === where.keyHash ? apiKey : null,
            update: async () => apiKey,
        },
        document: {
            findFirst: async () => doc,
            findMany: async () => [],
            count: async () => 0,
        },
        user: {},
        session: {},
        media: {},
    };
}
const PAGE_DOC = {
    id: 'doc-1',
    collection: 'pages',
    title: 'Hello',
    slug: 'hello',
    data: { content: 'Some body content for analysis.' },
    createdAt: new Date(),
    updatedAt: new Date(),
};
describe('GET /seo/analysis access control', () => {
    beforeEach(() => {
        delete globalThis.__actuateConfig;
        process.env.CMS_SECRET = VALID_SECRET;
    });
    it('returns 403 when the collection access.read rule denies the user', async () => {
        const { key, record } = await makeKey({ collections: ['pages'], actions: ['read'] });
        const db = createMockDB(record, PAGE_DOC);
        initDB(db);
        const handler = handleActuateAPI({
            prismaClient: db,
            config: { collections: { pages: { access: { read: () => false } } } },
        });
        const res = await handler(new Request('https://x.com/api/cms/seo/analysis/doc-1', {
            headers: { Authorization: `Bearer ${key}` },
        }));
        expect(res.status).toBe(403);
    });
    it('returns 200 when the collection access.read rule allows the user', async () => {
        const { key, record } = await makeKey({ collections: ['pages'], actions: ['read'] });
        const db = createMockDB(record, PAGE_DOC);
        initDB(db);
        const handler = handleActuateAPI({
            prismaClient: db,
            config: { collections: { pages: { access: { read: () => true } } } },
        });
        const res = await handler(new Request('https://x.com/api/cms/seo/analysis/doc-1', {
            headers: { Authorization: `Bearer ${key}` },
        }));
        expect(res.status).toBe(200);
    });
    it('rejects an API key without read scope on the collection (403)', async () => {
        const { key, record } = await makeKey({ collections: ['posts'], actions: ['read'] });
        const db = createMockDB(record, PAGE_DOC);
        initDB(db);
        const handler = handleActuateAPI({
            prismaClient: db,
            config: { collections: { pages: { access: { read: () => true } } } },
        });
        const res = await handler(new Request('https://x.com/api/cms/seo/analysis/doc-1', {
            headers: { Authorization: `Bearer ${key}` },
        }));
        expect(res.status).toBe(403);
    });
});
//# sourceMappingURL=seo-read-access.test.js.map