import '@angular/compiler';
import { Injector, runInInjectionContext } from '@angular/core';
import { TranslocoService } from '@jsverse/transloco';
import { auroraGraphqlErrorHandlerFactory } from './aurora-graphql-error.handler';

const { toastError } = vi.hoisted(() => ({ toastError: vi.fn() }));
vi.mock('@spartan-ng/brain/sonner', () => ({ toast: { error: toastError } }));

function setup() {
  const translate = vi.fn().mockReturnValue('Something went wrong');
  const injector = Injector.create({
    providers: [{ provide: TranslocoService, useValue: { translate } }],
  });
  const handler = runInInjectionContext(injector, () => auroraGraphqlErrorHandlerFactory());
  return { handler, translate };
}

describe('auroraGraphqlErrorHandlerFactory', () => {
  beforeEach(() => toastError.mockClear());

  it('shows a toast for each GraphQL error message', () => {
    const { handler } = setup();

    handler.handleGraphQLErrors([
      { statusCode: 400, message: 'First' },
      { statusCode: 409, message: 'Second' },
    ]);

    expect(toastError).toHaveBeenCalledTimes(2);
    expect(toastError).toHaveBeenNthCalledWith(1, 'First');
    expect(toastError).toHaveBeenNthCalledWith(2, 'Second');
  });

  it('toasts a generic translated message and logs on network error', () => {
    const { handler, translate } = setup();
    const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);

    handler.handleNetworkError(new Error('boom'), 500);

    expect(translate).toHaveBeenCalledWith('SomethingWentWrong');
    expect(toastError).toHaveBeenCalledWith('Something went wrong');
    expect(consoleError).toHaveBeenCalled();

    consoleError.mockRestore();
  });
});
