const { SESClient, SendEmailCommand } = require("@aws-sdk/client-ses"); const fs = require("fs").promises; const path = require("path"); const { getAWSConfig } = require("../config/aws"); const { User } = require("../models"); class EmailService { constructor() { this.sesClient = null; this.initialized = false; this.templates = new Map(); } async initialize() { if (this.initialized) return; try { // Use centralized AWS configuration with credential profiles const awsConfig = getAWSConfig(); this.sesClient = new SESClient(awsConfig); await this.loadEmailTemplates(); this.initialized = true; console.log("SES Email Service initialized successfully"); } catch (error) { console.error("Failed to initialize SES Email Service:", error); throw error; } } async loadEmailTemplates() { const templatesDir = path.join(__dirname, "..", "templates", "emails"); try { const templateFiles = [ "conditionCheckReminderToUser.html", "rentalConfirmationToUser.html", "emailVerificationToUser.html", "passwordResetToUser.html", "passwordChangedToUser.html", "lateReturnToCS.html", "damageReportToCS.html", "lostItemToCS.html", "rentalRequestToOwner.html", "rentalRequestConfirmationToRenter.html", "rentalCancellationConfirmationToUser.html", "rentalCancellationNotificationToUser.html", "rentalDeclinedToRenter.html", "rentalApprovalConfirmationToOwner.html", "rentalCompletionThankYouToRenter.html", "rentalCompletionCongratsToOwner.html", "payoutReceivedToOwner.html", "firstListingCelebrationToOwner.html", ]; for (const templateFile of templateFiles) { try { const templatePath = path.join(templatesDir, templateFile); const templateContent = await fs.readFile(templatePath, "utf-8"); const templateName = path.basename(templateFile, ".html"); this.templates.set(templateName, templateContent); console.log(`✓ Loaded template: ${templateName}`); } catch (error) { console.error(`✗ Failed to load template ${templateFile}:`, error.message); console.error(` Template path: ${path.join(templatesDir, templateFile)}`); } } console.log(`Loaded ${this.templates.size} of ${templateFiles.length} email templates`); } catch (error) { console.warn("Templates directory not found, using fallback templates"); } } /** * Convert HTML to plain text for email fallback * Strips HTML tags and formats content for plain text email clients */ htmlToPlainText(html) { return ( html // Remove style and script tags and their content .replace(/