import { describe, it, expect, beforeEach } from 'vitest';
import { LogRelay } from '../log-relay.js';

describe('LogRelay', () => {
  let relay: LogRelay;

  beforeEach(() => {
    relay = new LogRelay();
  });

  it('appends log lines to per-host tail', () => {
    relay.append('host1', 'proxy', 'connection established');
    relay.append('host1', 'upstream', 'request completed');

    const tail = relay.getTail('host1');
    expect(tail).toHaveLength(2);
    expect(tail[0].source).toBe('proxy');
    expect(tail[1].source).toBe('upstream');
  });

  it('trims tail to MAX_LOG_LINES (2000)', () => {
    for (let i = 0; i < 2500; i++) {
      relay.append('host1', 'proxy', `line ${i}`);
    }

    const tail = relay.getTail('host1');
    expect(tail.length).toBe(2000);
    expect(tail[0].line).toBe('line 500');
    expect(tail[tail.length - 1].line).toBe('line 2499');
  });

  it('returns empty array for unknown host', () => {
    expect(relay.getTail('unknown')).toEqual([]);
  });

  it('getAllTails returns lines from all hosts', () => {
    relay.append('host1', 'proxy', 'line1');
    relay.append('host2', 'upstream', 'line2');

    const all = relay.getAllTails();
    expect(all).toHaveLength(2);
    expect(all.map((l) => l.providerId)).toContain('host1');
    expect(all.map((l) => l.providerId)).toContain('host2');
  });

  it('getSources returns unique source values', () => {
    relay.append('host1', 'proxy', 'line1');
    relay.append('host1', 'upstream', 'line2');
    relay.append('host2', 'model', 'line3');

    const sources = relay.getSources();
    expect(sources).toContain('proxy');
    expect(sources).toContain('upstream');
    expect(sources).toContain('model');
    expect(sources.length).toBe(3);
  });

  it('timestamps are set on each line', () => {
    relay.append('host1', 'proxy', 'test');
    const tail = relay.getTail('host1');
    expect(tail[0].ts).toBeInstanceOf(Date);
  });
});
