import { Render } from 'mweb/server/renderer';
import { returnStatus, StatusCode } from 'mweb/common/reducers/root';
import { getCacheControlHeader } from 'mweb/server/selectors/cache';

export function respondThroughCallback(
  callback: AWS.Lambda.Callback<any>,
  { html, state }: Render,
): void {
  const cacheControl = getCacheControlHeader(state);
  switch (returnStatus(state)) {
    case StatusCode.SUCCESS:
      callback(null, { html, headers: { cacheControl } });
      break;
    case StatusCode.NOT_FOUND:
      callback(
        JSON.stringify({
          status: 'not found',
          html,
          headers: { cacheControl },
        }),
        null,
      );
      break;
    default:
      callback(
        JSON.stringify({
          status: 'Internal server error',
          html,
          headers: { cacheControl },
        }),
        null,
      );
      break;
  }
}
