import { PageView, type EntityType } from '@core/analytics/domain/entities/PageView';

describe('PageView', () => {
  const now = new Date('2025-01-01T12:00:00.000Z');

  const createValid = (overrides?: Partial<Parameters<typeof PageView.create>[0]>) => {
    return PageView.create({
      id: 'pv_1',
      entityType: 'league',
      entityId: 'entity_123',
      visitorType: 'anonymous',
      sessionId: 'session_1',
      timestamp: now,
      ...overrides,
    });
  };

  it('creates a PageView and exposes value-object values', () => {
    const pv = createValid({
      id: '   pv_123   ',
      entityId: '   entity_456   ',
      sessionId: '   session_789   ',
    });

    expect(pv.id).toBe('pv_123');
    expect(pv.entityId).toBe('entity_456');
    expect(pv.sessionId).toBe('session_789');
    expect(pv.timestamp).toEqual(now);
  });

  it('throws if id is missing', () => {
    expect(() => createValid({ id: '' })).toThrow(Error);
    expect(() => createValid({ id: '   ' })).toThrow(Error);
  });

  it('throws if entityType is missing', () => {
    expect(() => createValid({ entityType: undefined as unknown as EntityType })).toThrow(Error);
  });

  it('throws if entityId is missing', () => {
    expect(() => createValid({ entityId: '' })).toThrow(Error);
    expect(() => createValid({ entityId: '   ' })).toThrow(Error);
  });

  it('throws if sessionId is missing', () => {
    expect(() => createValid({ sessionId: '' })).toThrow(Error);
    expect(() => createValid({ sessionId: '   ' })).toThrow(Error);
  });

  it('withDuration returns a new PageView with duration', () => {
    const pv = createValid({ visitorId: 'visitor-1' });

    const pv2 = pv.withDuration(12_345);

    expect(pv2).not.toBe(pv);
    expect(pv2.durationMs).toBe(12_345);
    expect(pv2.id).toBe(pv.id);
    expect(pv2.sessionId).toBe(pv.sessionId);
  });

  it('withDuration throws for negative durations', () => {
    const pv = createValid();
    expect(() => pv.withDuration(-1)).toThrow(Error);
  });

  it('isMeaningfulView is true for 5s+ duration', () => {
    expect(createValid({ durationMs: 4999 }).isMeaningfulView()).toBe(false);
    expect(createValid({ durationMs: 5000 }).isMeaningfulView()).toBe(true);
  });

  it('isExternalReferral checks referrer domain', () => {
    expect(createValid().isExternalReferral()).toBe(false);
    expect(createValid({ referrer: 'https://gridpilot.example/path' }).isExternalReferral()).toBe(false);
    expect(createValid({ referrer: 'https://example.com/path' }).isExternalReferral()).toBe(true);
  });
});