import { describe, it, expect } from 'vitest';
import { buildSeries, unitForDays, truncUtc } from './series';
import type { MetricsBucket } from '$lib/api/admin';

function bucket(t: string, n: number, ok: number, avg: number | null): MetricsBucket {
    return { t, n, ok, failed: n - ok, avg_ms: avg };
}

describe('series helpers', () => {
    it('picks hour vs day by window', () => {
        expect(unitForDays(1)).toBe('hour');
        expect(unitForDays(2)).toBe('hour');
        expect(unitForDays(7)).toBe('day');
        expect(unitForDays(0)).toBe('day');
    });

    it('truncUtc snaps to hour/day boundaries', () => {
        const ms = Date.parse('2026-06-18T09:37:42Z');
        expect(new Date(truncUtc(ms, 'hour')).toISOString()).toBe('2026-06-18T09:00:00.000Z');
        expect(new Date(truncUtc(ms, 'day')).toISOString()).toBe('2026-06-18T00:00:00.000Z');
    });

    it('fills empty buckets: throughput 0, success/duration null', () => {
        // days=2 → hourly. Provide data only at 10:00; 11:00 must be a gap.
        const now = Date.parse('2026-06-18T11:30:00Z');
        const buckets = [bucket('2026-06-18T10:00:00Z', 4, 3, 200)];
        const s = buildSeries(buckets, 2, now);
        // Find the 10:00 and 11:00 slots.
        const at10 = s.throughput.findIndex((p) => p.t === '2026-06-18T10:00:00.000Z');
        expect(at10).toBeGreaterThanOrEqual(0);
        expect(s.throughput[at10].value).toBe(4);
        expect(s.success[at10].value).toBe(75); // 3/4
        expect(s.duration[at10].value).toBe(200);

        const at11 = s.throughput.findIndex((p) => p.t === '2026-06-18T11:00:00.000Z');
        expect(s.throughput[at11].value).toBe(0); // no ops → zero throughput
        expect(s.success[at11].value).toBeNull(); // no denominator → gap
        expect(s.duration[at11].value).toBeNull();
    });

    it('all-time spans only the data present', () => {
        const buckets = [
            bucket('2026-06-10T00:00:00Z', 1, 1, 100),
            bucket('2026-06-12T00:00:00Z', 1, 0, 100)
        ];
        const s = buildSeries(buckets, 0);
        // 10th, 11th (gap), 12th → 3 day slots.
        expect(s.throughput.length).toBe(3);
        expect(s.throughput[1].value).toBe(0);
    });
});
