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';
/**
 * Contract tests for the appearance/brand endpoints:
 *   - GET /public/brand  → public, exposes ONLY the public brand + favicon.
 *   - GET /appearance     → authed, exposes stored settings + resolved views.
 *
 * Pins the response shapes the public frontend and admin Appearance tab depend
 * on, and proves the public route never leaks the admin-only brand.
 */
const VALID_SECRET = 'a'.repeat(48);
const SETTINGS_BLOB = {
    siteTitle: 'Actuate Media',
    brand: {
        mode: 'customAdminBrand',
        publicPrimaryLogoAssetId: 'pub-logo',
        adminPrimaryLogoAssetId: 'admin-logo',
        faviconSourceAssetId: 'fav',
        updatedAt: '2026-02-03T00:00:00.000Z',
    },
    appearance: { adminAccentColor: 'teal', sidebarDensity: 'compact', reduceMotion: true },
};
const MEDIA_ROWS = [
    {
        id: 'pub-logo',
        publicUrl: 'https://cdn.example.com/pub.svg',
        mimeType: 'image/svg+xml',
        width: 400,
        height: 100,
    },
    {
        id: 'admin-logo',
        publicUrl: 'https://cdn.example.com/admin.svg',
        mimeType: 'image/svg+xml',
        width: 380,
        height: 90,
    },
    {
        id: 'fav',
        publicUrl: 'https://cdn.example.com/fav.png',
        mimeType: 'image/png',
        width: 32,
        height: 32,
    },
];
function createMockDB(opts = {}) {
    const apiKey = opts.apiKey;
    return {
        apiKey: {
            findMany: async () => (apiKey ? [apiKey] : []),
            findUnique: async ({ where }) => apiKey && apiKey.keyHash === where.keyHash ? apiKey : null,
            update: async () => apiKey,
        },
        document: {
            findFirst: async () => ({ data: SETTINGS_BLOB }),
            findMany: async () => [],
            count: async () => 0,
        },
        media: {
            findMany: async () => MEDIA_ROWS,
        },
        user: {},
        session: {},
    };
}
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,
        },
    };
}
describe('GET /public/brand', () => {
    beforeEach(() => {
        delete globalThis.__actuateConfig;
        process.env.CMS_SECRET = VALID_SECRET;
    });
    it('returns the public brand + favicon without auth and hides the admin brand', async () => {
        const db = createMockDB();
        initDB(db);
        const handler = handleActuateAPI({ prismaClient: db, config: { collections: {} } });
        const res = await handler(new Request('https://example.com/api/cms/public/brand'));
        expect(res.status).toBe(200);
        const body = (await res.json());
        expect(body.data.public.primary.url).toBe('https://cdn.example.com/pub.svg');
        expect(body.data.favicon.icon).toContain('/api/cms/public/brand/favicon?v=');
        // The admin-only brand must NOT be exposed publicly.
        expect(body.data.admin).toBeUndefined();
        expect(JSON.stringify(body)).not.toContain('admin.svg');
    });
});
describe('GET /appearance', () => {
    beforeEach(() => {
        delete globalThis.__actuateConfig;
        process.env.CMS_SECRET = VALID_SECRET;
    });
    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/appearance'));
        expect(res.status).toBe(401);
    });
    it('returns stored appearance + brand + resolved admin/public views when authed', async () => {
        const { key, record } = await makeKey({ admin: true });
        const db = createMockDB({ apiKey: record });
        initDB(db);
        const handler = handleActuateAPI({ prismaClient: db, config: { collections: {} } });
        const res = await handler(new Request('https://example.com/api/cms/appearance', {
            headers: { Authorization: `Bearer ${key}` },
        }));
        expect(res.status).toBe(200);
        const body = (await res.json());
        expect(body.data.appearance.adminAccentColor).toBe('teal');
        expect(body.data.appearance.sidebarDensity).toBe('compact');
        expect(body.data.brand.mode).toBe('customAdminBrand');
        // customAdminBrand → admin primary resolves to the admin asset.
        expect(body.data.resolved.admin.primary.url).toBe('https://cdn.example.com/admin.svg');
        expect(body.data.resolved.public.primary.url).toBe('https://cdn.example.com/pub.svg');
    });
});
//# sourceMappingURL=appearance-routes.test.js.map