import { render } from '@testing-library/react';
import React from 'react';
import { describe, expect, it } from 'vitest';
import { StationError } from '../components/models';
import { ErrorTypeToStationError } from './ErrorTypeToStationError';

describe('ErrorTypeToStationError', () => {
  it('returns a correct StationError if getting one', () => {
    const error: StationError = {
      title: 'test',
    };
    const result = ErrorTypeToStationError(error);
    expect(result).toBe(error);

    const error2: StationError = {
      title: 'test',
      body: 'test body',
    };
    const result2 = ErrorTypeToStationError(error2);
    expect(result2).toBe(error2);

    const { container } = render(<>{result2.body}</>);

    expect(container.textContent).toContain('test body');
  });

  it('returns a correct StationError if getting a string', () => {
    const error = 'test';
    const result = ErrorTypeToStationError(error);
    expect(result.title).toBe('An error occurred.');
    const { container } = render(<>{result.body}</>);

    expect(container.textContent).toContain('test');
  });

  it('returns a correct StationError if getting an object', () => {
    const error = { my: 'value' };
    const result = ErrorTypeToStationError(error);
    expect(result.title).toBe('An error occurred.');
    const { container } = render(<>{result.body}</>);

    expect(container.textContent).toContain(`"my": "value"`);
  });

  it('returns a correct StationError if getting an Error', () => {
    const error = new Error('test error');
    const result = ErrorTypeToStationError(error);
    expect(result.title).toBe('An error occurred.');
    const { container } = render(<>{result.body}</>);

    expect(container.textContent).toContain('Error: test error');
  });

  it('allows overwriting the title', () => {
    const error = new Error('test error');
    const result = ErrorTypeToStationError(error, 'custom title');
    expect(result.title).toBe('custom title');
  });

  it('uses the apollo mapper by default', () => {
    const error = {
      name: 'ApolloError',
      networkError: { message: 'test error' },
    };
    const result = ErrorTypeToStationError(error);
    expect(result.title).toBe('A network error occurred');
    const { container } = render(<>{result.body}</>);

    expect(container.textContent).toContain('test error');
  });
});
