import createTestState from 'mtest/helpers/createTestState';
import expect from 'expect';
import { captureConsoleOutput } from 'mtest/helpers/captureConsoleOutput';

import { LogLevel, LogOutput } from 'tachyon-logger';
import { getLoggingCallback } from 'mweb/lambda/callback-decorator';
import { Location, ErrorCondition } from 'mweb/common/reducers/app';
import omit from 'lodash-es/omit';

function captureLogWithoutTime(func: () => any): LogOutput {
  const output = captureConsoleOutput(func)[0];
  const parsedOutput =
    typeof window !== 'undefined' ? output : JSON.parse(output);
  return omit(parsedOutput, 'time') as LogOutput;
}

describe('logging callback', () => {
  const callback = (_: any, __: string | null): void => {
    return;
  };

  it('always logs empty state and errorCondition as success', () => {
    expect(
      captureLogWithoutTime(() => {
        getLoggingCallback(callback)(null, null);
      }),
    ).toEqual({
      level: LogLevel.INFO,
      message: { isError: false, location: undefined },
    });
  });

  it('logs location on success', () => {
    const state = createTestState({
      app: {
        location: Location.Channel,
      },
    });
    expect(
      captureLogWithoutTime(() => {
        getLoggingCallback(callback, state)(null, null);
      }),
    ).toEqual({
      level: LogLevel.INFO,
      message: { isError: false, location: Location.Channel },
    });
  });

  it('logs errors when errorCondition is set on state', () => {
    const state = createTestState({
      app: {
        location: Location.Channel,
        errorCondition: ErrorCondition.ApiError,
      },
    });
    expect(
      captureLogWithoutTime(() => {
        getLoggingCallback(callback, state)(null, null);
      }),
    ).toEqual({
      level: LogLevel.ERROR,
      message: {
        isError: true,
        location: Location.Channel,
        errorCondition: ErrorCondition.ApiError,
      },
    });
  });
});
