"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0});exports.templateEngine=exports.TemplateEngine=void 0;const db_1=require("@b/db"),console_1=require("@b/utils/console"),ejs_1=__importDefault(require("ejs"));class TemplateEngine{constructor(){this.templateCache=new Map;this.CACHE_TTL=3e5}static getInstance(){TemplateEngine.instance||(TemplateEngine.instance=new TemplateEngine);return TemplateEngine.instance}async render(e,t){try{const n=await this.getTemplate(e);if(!n)throw new Error(`Template '${e}' not found`);const r=this.renderString(n.subject,t),a=this.renderString(n.body,t),l=this.stripHtml(a);console_1.logger.info("TemplateEngine",`Template rendered successfully: ${e}`,JSON.stringify({templateName:e,subject:r}));return{subject:r,html:a,text:l}}catch(t){console_1.logger.error("TemplateEngine",`Failed to render template: ${e}`,t instanceof Error?t:new Error(String(t)));throw t}}async getTemplate(e){const t=this.templateCache.get(e);if(t&&Date.now()-t.timestamp<this.CACHE_TTL)return t.template;try{const t=await db_1.models.emailTemplate.findOne({where:{name:e,status:!0}});t&&this.templateCache.set(e,{template:t,timestamp:Date.now()});return t}catch(t){console_1.logger.error("TemplateEngine",`Failed to load template from database: ${e}`,t instanceof Error?t:new Error(String(t)));return null}}renderString(e,t){try{return ejs_1.default.render(e,t,{escape:e=>this.escapeHtml(e)})}catch(e){console_1.logger.error("TemplateEngine","Failed to render template string",e instanceof Error?e:new Error(String(e)));throw e}}escapeHtml(e){const t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;"};return e.replace(/[&<>"'/]/g,e=>t[e])}stripHtml(e){return e.replace(/<style[^>]*>.*<\/style>/gims,"").replace(/<script[^>]*>.*<\/script>/gims,"").replace(/<[^>]+>/gm,"").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#x27;/g,"'").replace(/&#x2F;/g,"/").replace(/\n\s*\n/g,"\n\n").trim()}clearCache(e){if(e){this.templateCache.delete(e);console_1.logger.info("TemplateEngine",`Template cache cleared: ${e}`)}else{this.templateCache.clear();console_1.logger.info("TemplateEngine","All template cache cleared")}}async preloadTemplates(e){console_1.logger.info("TemplateEngine",`Preloading templates: ${e.length}`);await Promise.all(e.map(e=>this.getTemplate(e).catch(t=>{console_1.logger.warn("TemplateEngine",`Failed to preload template: ${e}`,t instanceof Error?t.message:String(t))})));console_1.logger.info("TemplateEngine","Templates preloaded successfully")}async renderWithFallback(e,t,n){try{return await this.render(e,t)}catch(r){if(n){console_1.logger.warn("TemplateEngine",`Using fallback template: ${e}`,r instanceof Error?r.message:String(r));return{subject:this.renderString(n.subject,t),html:this.renderString(n.body,t),text:this.stripHtml(this.renderString(n.body,t))}}throw r}}createSimpleEmail(e,t,n){const r=`\n<!DOCTYPE html>\n<html>\n<head>\n  <meta charset="UTF-8">\n  <meta name="viewport" content="width=device-width, initial-scale=1.0">\n  <title>${this.escapeHtml(e)}</title>\n</head>\n<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">\n  <div style="background-color: #f4f4f4; padding: 20px; border-radius: 5px;">\n    <h2 style="color: #333; margin-top: 0;">${this.escapeHtml(e)}</h2>\n    <div style="background-color: white; padding: 20px; border-radius: 5px;">\n      <p>${this.escapeHtml(t)}</p>\n      ${n?`\n      <div style="margin-top: 20px; padding-top: 20px; border-top: 1px solid #eee;">\n        ${Object.entries(n).map(([e,t])=>`<p><strong>${this.escapeHtml(e)}:</strong> ${this.escapeHtml(String(t))}</p>`).join("")}\n      </div>\n      `:""}\n    </div>\n    <div style="margin-top: 20px; text-align: center; color: #666; font-size: 12px;">\n      <p>This is an automated message, please do not reply.</p>\n    </div>\n  </div>\n</body>\n</html>\n    `.trim();return{subject:e,html:r,text:this.stripHtml(r)}}}exports.TemplateEngine=TemplateEngine;exports.templateEngine=TemplateEngine.getInstance();