import { routeTests, TestHelpers } from '@squiz/render-runtime-lib';
import { startDevelopmentRender } from './component-dev';
import supertest from 'supertest';
import { Server } from 'http';

jest.setTimeout(20_000);

describe('component-dev', () => {
  describe('accessing local dev routes', () => {
    let server: Server;
    let request: supertest.SuperTest<supertest.Test>;

    beforeAll(async () => {
      server = startDevelopmentRender(TestHelpers.getTestComponentFolder(), { port: 0, noBrowser: true });
      request = supertest(server);
    });

    afterAll(async () => {
      server.close();
    });

    it('should fail validation when requesting a function with a missing entry file', async () => {
      const response = await request.get(
        '/r/unit-test-components/test-component/1.0.3/main?_componentSet=set&something=not-used',
      );

      expect(response.body).toEqual({
        message: '"main\'s" entry file "missing-entry-file.js" is inaccessible',
      });
      expect(response.statusCode).toEqual(500);
    });

    describe('definition routes', () => {
      routeTests.definition(() => request, 'http://localhost:0');
    });

    describe('static routes', () => {
      routeTests.static(() => request);
    });

    describe('render routes', () => {
      routeTests.render(() => request, 'http://localhost:0');
    });

    describe('preview tests', () => {
      routeTests.preview(() => request, 'http://localhost:0');
    });

    describe('user experience', () => {
      describe('on navigation to a component without preview from home page it should still try and render by default', () => {
        it('should successfully try to render a component with a dummy set', async () => {
          const listingResponse = await request.get('/');
          // Component with no preview
          expect(listingResponse.text).toContain(
            '/r/unit-test-components/test-component/1.0.10?_componentSet=local-development-only',
          );

          const renderResponse = await request.get(
            '/r/unit-test-components/test-component/1.0.10?_componentSet=local-development-only',
          );

          expect(renderResponse.statusCode).toEqual(200);
        });
      });
    });
  });
});
