import { HttpErrorInterceptor } from './http-error.interceptor';
import { createServiceFactory, SpectatorService } from '@ngneat/spectator';
import { UiErrorModalComponent, UiMessageModalComponent, UiModalService } from '@ui/modal';
import { throwError } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';

describe('HttpErrorInterceptor', () => {
  let spectator: SpectatorService<HttpErrorInterceptor>;
  let modalMock: jasmine.SpyObj<UiModalService>;
  let httpErrorInterceptor: HttpErrorInterceptor;

  const createService = createServiceFactory({
    service: HttpErrorInterceptor,
    mocks: [UiModalService],
  });

  beforeEach(() => {
    spectator = createService();
    httpErrorInterceptor = spectator.service;
    modalMock = spectator.inject(UiModalService);
  });

  it('should be created', () => {
    expect(httpErrorInterceptor).toBeTruthy();
  });

  describe('intercept', () => {
    it('should catch the error and call handleError', (done) => {
      const error = new HttpErrorResponse({
        status: 0,
        statusText: '',
        url: '',
      });
      const handleErrorSpy = spyOn(httpErrorInterceptor, 'handleError').and.callThrough();
      httpErrorInterceptor.intercept(null, { handle: () => throwError(error) }).subscribe({
        error: () => {
          expect(handleErrorSpy).toHaveBeenCalledWith(error);
          done();
        },
      });
    });
  });

  describe('handleError', () => {
    it('should call modal.open with offline message if status is 0', () => {
      const error = {
        error: {
          message: 'test',
        },
        status: 0,
      };
      httpErrorInterceptor.handleError(error as any);
      expect(modalMock.open).toHaveBeenCalledWith({
        content: UiMessageModalComponent,
        title: 'Sie sind offline, keine Verbindung zum Netzwerk',
        data: { message: 'Bereits geladene Inhalte werden angezeigt. Interaktionen sind aktuell nicht möglich.' },
      });
    });
  });
});
