const handlebars = require('handlebars');
const fs = require('fs');
const { promisify } = require('util');
const Hoek = require('hoek');
const bookshelf = require('../../lib/bookshelf');

module.exports = () => ({
  async fetchTemplate(clientId, page) {
    Hoek.assert(clientId, new Error('clientId is required in ThemeService::fetchTemplate'));

    const client = await bookshelf.model('client')
      .where({client_id: clientId})
      .fetch({ withRelated: ['theme.templates.layout'] });

    // scenario 1, client has null theme
    if (!client.get('theme_id')) return false;

    // scenario 2, client has theme but null template
    const template = client.related('theme').related('templates').find(template => template.get('name') === page);
    return template || false;
  },

  async getThemedTemplate(clientId, page, context) {
    Hoek.assert(clientId, new Error('clientId is required in ThemeService::getThemedTemplate'));
    const template = await this.fetchTemplate(clientId, page);
    if (!template) return false;

    const renderedTemplate = await template.render(page, context);
    // const serializedTemplate = template.serialize();

    // serializedTemplate.rendered_code = renderedTemplate;
    // return serializedTemplate;

    return {
      template,
      renderedTemplate,
    }
  },

  async renderThemedTemplate(clientId, page, context) {
    Hoek.assert(clientId, new Error('clientId is required in ThemeService::renderThemedTemplate'));

    const template = await this.fetchTemplate(clientId, page);
    if (!template) return false;

    const renderedTemplate = await template.render(page, context);
    return renderedTemplate;
  }
});

module.exports['@singleton'] = true;
module.exports['@require'] = [];

@@ -1,111 +1,4 @@
-const handlebars = require('handlebars');%0Aconst fs = require('fs');%0Aconst %7B promisify %7D = require('util');%0A
 cons
@@ -23,16 +23,16 @@
 hoek');%0A
+
 const bo
@@ -338,51 +338,8 @@
 tch(
-%7B withRelated: %5B'theme.templates.layout'%5D %7D
 );%0A%0A
@@ -506,39 +506,29 @@
 e = 
-client.related('theme').related
+await bookshelf.model
 ('te
@@ -537,61 +537,119 @@
 late
-s
 ').
-find(template =%3E
+where(%7B%0A     
  t
+h
 em
-plate.get('name') === page
+e_id: client.get('theme_id'),%0A      name: page,%0A    %7D).fetch(%7BwithRelated: %5B'layout'%5D%7D
 );%0A
+%0A
     
@@ -997,159 +997,8 @@
 xt);
-%0A    // const serializedTemplate = template.serialize();%0A%0A    // serializedTemplate.rendered_code = renderedTemplate;%0A    // return serializedTemplate;
 %0A%0A  
@@ -1048,21 +1048,22 @@
 mplate,%0A
-
     %7D
+;
 %0A  %7D,%0A%0A 

Fix template query