import React from 'react';
import { renderToString, renderToNodeStream } from 'react-dom/server';

import Html from './HTML';

import { handleRender } from './utils';

export const serverRenderer = () => async (req, res): void => {
  const renderData = await handleRender(req, res, true);

  // null when there is a redirection
  if (!renderData) return;

  const { content, state, scriptElements, linkElements, styleElements } = renderData;

  // very important or it sents plain text
  res.setHeader('content-type', 'text/html');
  res.write('<!DOCTYPE html>');
  renderToNodeStream(
    <Html
      scriptElements={scriptElements}
      linkElements={linkElements}
      styleElements={styleElements}
      state={state}
    >
      {content}
    </Html>,
  ).pipe(res);
};

export default serverRenderer;
