import { describe, expect, it } from 'vitest' import { recordUsage, type UsageEvent } from '@/shared/api/usage/server' const config = { baseUrl: 'https://console.example.com', token: 'dt_fixture' } const event: UsageEvent = { idempotency_key: 'upload:f1', customer: { external_id: 'showcase' }, meter: 'uploads', quantity: '1', } describe('recordUsage', () => { it('posts one batch to the token route with the token as a bearer credential', async () => { const calls: { url: string; init: RequestInit }[] = [] const fetcher = (async (url: string, init: RequestInit) => { calls.push({ url, init }) return new Response(JSON.stringify({ accepted: 1, duplicates: 0, rejected: [] }), { status: 202 }) }) as typeof fetch const result = await recordUsage(config, [event], fetcher) expect(result).toEqual({ accepted: 1, duplicates: 0, rejected: [] }) expect(calls).toHaveLength(1) expect(calls[0]?.url).toBe('https://console.example.com/_conusai/usage/events') expect(calls[0]?.init.method).toBe('POST') expect(new Headers(calls[0]?.init.headers).get('authorization')).toBe('Bearer dt_fixture') expect(JSON.parse(String(calls[0]?.init.body))).toEqual({ events: [event] }) }) it('treats anything but 202 as a failure, so the caller can resend the same key', async () => { const fetcher = (async () => new Response('{}', { status: 403 })) as typeof fetch await expect(recordUsage(config, [event], fetcher)).rejects.toThrow(/403/) }) })