import { afterEach, 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';
/**
 * Contract tests for GET /ai/status.
 *
 * The AI tab in the admin is read-only: AI is configured server-side via the
 * plugin + environment variables, never from the dashboard. This endpoint
 * powers an honest status panel, so it must:
 *   - require an authenticated admin,
 *   - return a `{ installed, configured, provider }` shape,
 *   - only hint at which provider env var is present (never the key value).
 */
const VALID_SECRET = 'a'.repeat(48);
function createMockDB(apiKey) {
    return {
        apiKey: {
            findMany: async () => (apiKey ? [apiKey] : []),
            findUnique: async ({ where }) => apiKey && apiKey.keyHash === where.keyHash ? apiKey : null,
            update: async () => apiKey,
        },
        document: {
            findFirst: async () => null,
            findMany: async () => [],
            count: async () => 0,
        },
        user: {
            findMany: async () => [],
            findUnique: async () => null,
            count: async () => 1,
        },
        auditLog: { create: async () => ({ id: 'log1' }), count: async () => 0 },
    };
}
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,
        },
    };
}
beforeEach(() => {
    delete globalThis.__actuateConfig;
    process.env.CMS_SECRET = VALID_SECRET;
});
afterEach(() => {
    delete process.env.ANTHROPIC_API_KEY;
    delete process.env.OPENAI_API_KEY;
});
describe('GET /ai/status', () => {
    it('requires authentication', async () => {
        const db = createMockDB();
        initDB(db);
        const handler = handleActuateAPI({ prismaClient: db, config: { collections: {} } });
        const res = await handler(new Request('https://example.com/api/cms/ai/status'));
        expect(res.status).toBe(401);
    });
    it('rejects non-admin API keys', async () => {
        const { key, record } = await makeKey({ media: true });
        const db = createMockDB(record);
        initDB(db);
        const handler = handleActuateAPI({ prismaClient: db, config: { collections: {} } });
        const res = await handler(new Request('https://example.com/api/cms/ai/status', {
            headers: { Authorization: `Bearer ${key}` },
        }));
        expect(res.status).toBe(403);
    });
    it('returns the status shape for an admin and never configures from the dashboard', async () => {
        const { key, record } = await makeKey({ admin: true });
        const db = createMockDB(record);
        initDB(db);
        const handler = handleActuateAPI({ prismaClient: db, config: { collections: {} } });
        const res = await handler(new Request('https://example.com/api/cms/ai/status', {
            headers: { Authorization: `Bearer ${key}` },
        }));
        expect(res.status).toBe(200);
        const body = (await res.json());
        expect(typeof body.data.installed).toBe('boolean');
        // No provider is registered in the test process, so it must report unconfigured.
        expect(body.data.configured).toBe(false);
        expect(body.data.provider).toBeNull();
    });
    it('hints at the configured provider env var without exposing the secret', async () => {
        process.env.ANTHROPIC_API_KEY = 'sk-ant-super-secret-value';
        const { key, record } = await makeKey({ admin: true });
        const db = createMockDB(record);
        initDB(db);
        const handler = handleActuateAPI({ prismaClient: db, config: { collections: {} } });
        const res = await handler(new Request('https://example.com/api/cms/ai/status', {
            headers: { Authorization: `Bearer ${key}` },
        }));
        expect(res.status).toBe(200);
        const body = (await res.json());
        expect(body.data.provider).toBe('anthropic');
        // The hint must never include the actual key value.
        expect(JSON.stringify(body)).not.toContain('sk-ant-super-secret-value');
    });
});
//# sourceMappingURL=ai-status.test.js.map