import { describe, expect, it } from 'vitest';
import { initDB } from '../../db.js';
import { logEvent, getAuditLog } from '../../security/audit.js';
function createMockDB() {
    const records = [];
    return {
        auditLog: {
            create: async ({ data }) => {
                const row = { ...data, id: `log-${records.length + 1}`, timestamp: new Date() };
                records.push(row);
                return row;
            },
            findMany: async ({ where, orderBy, skip, take }) => {
                let filtered = records;
                if (where?.event)
                    filtered = filtered.filter((r) => r.event === where.event);
                if (orderBy?.timestamp === 'desc') {
                    filtered = [...filtered].sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime());
                }
                return filtered.slice(skip ?? 0, (skip ?? 0) + (take ?? filtered.length));
            },
            count: async ({ where }) => {
                if (!where?.event)
                    return records.length;
                return records.filter((r) => r.event === where.event).length;
            },
        },
    };
}
describe('audit log', () => {
    it('logEvent stores an entry and getAuditLog reads it back', async () => {
        const db = createMockDB();
        initDB(db);
        await logEvent({ event: 'login_success', userId: 'u1', ipAddress: '203.0.113.5' });
        const result = await getAuditLog({ event: 'login_success' });
        expect(result.total).toBe(1);
        expect(result.entries[0]).toMatchObject({ event: 'login_success', userId: 'u1' });
    });
    it('getAuditLog orders by timestamp (regression: previously used non-existent createdAt column)', async () => {
        const db = createMockDB();
        initDB(db);
        await logEvent({ event: 'a' });
        await new Promise((r) => setTimeout(r, 5));
        await logEvent({ event: 'b' });
        const result = await getAuditLog({});
        expect(result.entries[0]?.event).toBe('b');
        expect(result.entries[1]?.event).toBe('a');
    });
});
//# sourceMappingURL=audit.test.js.map