import registerRequireContextHook from 'babel-plugin-require-context-hook/register';
import initStoryshots, { Stories2SnapsConverter } from '@storybook/addon-storyshots';
import Enzyme, { mount } from 'enzyme';
// eslint-disable-next-line import/no-extraneous-dependencies
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';

import toJson from 'enzyme-to-json';

registerRequireContextHook();

initStoryshots({
  asyncJest: true,
  configPath: 'config/storybook',
  test: ({ story, context, done }) => {
    Enzyme.configure({ adapter: new Adapter() });

    const converter = new Stories2SnapsConverter();
    const snapshotFilename = converter.getSnapshotFileName(context);
    const storyElement = story.render();

    // mount the story
    const tree = mount(storyElement);

    // wait for async updates
    const waitTime = 1000;

    setTimeout(() => {
      if (snapshotFilename) {
        tree.update();

        const component = tree.find('TestWrapper').last().children();

        expect(toJson(component)).toMatchSpecificSnapshot(snapshotFilename);
      }

      done();
    }, waitTime);
  }
});
