import fs from 'fs';
import path from 'path';

function injectMetaTags(templates) {
  let config;
  let template = fs.readFileSync(path.resolve('./src/meta-tags-header.html'), 'utf8');

  return {
    name: 'inject-meta-tags',
    configResolved(resolvedConfig) {
      config = resolvedConfig;

      // remove all ejs content in dev mode
      if (!config.isProduction) template = template.replace(/<%[^]*?%>/g, '');
    },
    transformIndexHtml: {
      handler: function transform(html, ctx) {
        if (templates.indexOf(ctx.filename) === -1) return html;

        html = html.replace(/<head(.*)>/i, `$&\n${template}`);

        return html;
      }
    },
  };
}

export default injectMetaTags;
