import { EmailService } from "@pkg/email";
import { type EmailPayload } from "$lib/domains/email/data/entities";
import { ERROR_CODES, type Result } from "@pkg/result";
import { getError } from "@pkg/logger";
import { env } from "$env/dynamic/private";

interface TemplateData {
	[key: string]: any;
}

interface EmailTemplatePayload {
	to: string;
	subject: string;
	template: string;
	templateData: TemplateData;
	from?: string;
	cc?: string[];
	bcc?: string[];
	attachments?: any[];
}

export class EmailerUseCases {
	apiKey: string;
	defaultSender: string;
	emailSvc: EmailService;

	constructor() {
		this.apiKey = env.RESEND_API_KEY ?? "";
		this.defaultSender = env.DEFAULT_EMAIL_SENDER ?? "";
		this.emailSvc = new EmailService();
	}

	async sendEmail(payload: EmailPayload): Promise<Result<boolean>> {
		try {
			// Set default sender if not provided
			if (!payload.from && this.defaultSender) {
				payload.from = this.defaultSender;
			}

			// Send the email
			return await this.emailSvc.sendEmail(payload, {
				apiKey: this.apiKey,
			});
		} catch (e) {
			return {
				error: getError(
					{
						code: ERROR_CODES.INTERNAL_SERVER_ERROR,
						message: "Failed to send email",
						userHint: "Please try again later",
						detail: "Error occurred during email sending",
					},
					e,
				),
			};
		}
	}

	async sendEmailWithTemplate(
		payload: EmailTemplatePayload,
	): Promise<Result<boolean>> {
		try {
			// Set default sender if not provided
			const from = payload.from || this.defaultSender;

			// Now we need to modify the ResendEmailSvcProvider to accept React components
			return await this.emailSvc.sendEmailWithReactTemplate(
				{
					to: payload.to,
					subject: payload.subject,
					from,
					cc: payload.cc,
					bcc: payload.bcc,
					attachments: payload.attachments,
					templateData: payload.templateData,
					template: payload.template,
				},
				{ apiKey: this.apiKey },
			);
		} catch (e) {
			return {
				error: getError(
					{
						code: ERROR_CODES.INTERNAL_SERVER_ERROR,
						message: "Failed to send email",
						userHint: "Please try again later",
						detail: "Error occurred during email template sending",
					},
					e,
				),
			};
		}
	}
}
