import { EmailProviders, type EmailProviderTypes, type EmailServiceProvider, type EmailPayload, } from "./src/data"; import { ERROR_CODES, type Result } from "@pkg/result"; import { getError } from "@pkg/logger"; import { ResendEmailSvcProvider } from "./src/resend.provider"; export class EmailService { private provider: EmailServiceProvider | null = null; initialize(apiKey: string): Result { try { this.provider = this.createProvider(EmailProviders.Resend, { apiKey }); return this.provider.initialize(); } catch (e) { return { error: getError( { code: ERROR_CODES.INTERNAL_SERVER_ERROR, message: "Failed to initialize email provider", userHint: "Please check email configuration", detail: "Error creating email provider", }, e, ), }; } } private createProvider( type: EmailProviderTypes, config: { apiKey: string }, ): EmailServiceProvider { switch (type) { case EmailProviders.Resend: return new ResendEmailSvcProvider(config.apiKey); default: throw new Error(`Unsupported email provider: ${type}`); } } async sendEmail( payload: EmailPayload, config: { apiKey: string }, ): Promise> { if (!this.provider) { const initResult = this.initialize(config.apiKey); if (initResult.error) return initResult; } return await this.provider!.sendEmail(payload); } async sendEmailWithReactTemplate( payload: { to: string; subject: string; from: string; cc?: string[]; bcc?: string[]; attachments?: any[]; template: string; templateData: any; }, config: { apiKey: string }, ): Promise> { if (!this.provider) { const initResult = this.initialize(config.apiKey); if (initResult.error) return initResult; } // This assumes you're using Resend as the provider if (this.provider instanceof ResendEmailSvcProvider) { return await this.provider.sendEmailWithReact(payload); } else { return { error: getError({ code: ERROR_CODES.INTERNAL_SERVER_ERROR, message: "React templates are only supported with the Resend provider", userHint: "Please configure Resend as your email provider", detail: "Current email provider doesn't support React templates", }), }; } } }