import type { Logger } from '@core/shared/domain/Logger';
import { describe, expect, it, vi, type Mock } from 'vitest';
import { GetAnalyticsMetricsUseCase, type GetAnalyticsMetricsInput } from './GetAnalyticsMetricsUseCase';

describe('GetAnalyticsMetricsUseCase', () => {
  let logger: Logger;
  let useCase: GetAnalyticsMetricsUseCase;

  beforeEach(() => {
    logger = {
      debug: vi.fn(),
      info: vi.fn(),
      warn: vi.fn(),
      error: vi.fn(),
    } as unknown as Logger;

    useCase = new GetAnalyticsMetricsUseCase(logger);
  });

  it('returns default metrics when no input is provided', async () => {
    const result = await useCase.execute();

    expect(result.isOk()).toBe(true);
    const data = result.unwrap();
    expect(data).toEqual({
      pageViews: 0,
      uniqueVisitors: 0,
      averageSessionDuration: 0,
      bounceRate: 0,
    });
    expect((logger.info as unknown as Mock)).toHaveBeenCalled();
  });

  it('uses provided date range and returns metrics', async () => {
    const input: GetAnalyticsMetricsInput = {
      startDate: new Date('2024-01-01'),
      endDate: new Date('2024-01-31'),
    };

    const result = await useCase.execute(input);

    expect(result.isOk()).toBe(true);
    const data = result.unwrap();
    expect(data.pageViews).toBe(0);
    expect((logger.info as unknown as Mock)).toHaveBeenCalled();
  });

  it('returns error when execute throws', async () => {
    const input: GetAnalyticsMetricsInput = {
      startDate: new Date('2024-01-01'),
      endDate: new Date('2024-01-31'),
    };

    // Simulate an error by temporarily spying on logger.info to throw
    (logger.info as unknown as Mock).mockImplementation(() => {
      throw new Error('Logging failed');
    });

    const result = await useCase.execute(input);

    expect(result.isErr()).toBe(true);
    expect((logger.error as unknown as Mock)).toHaveBeenCalled();
  });
});