import { StageId } from '@core/types'
import { MailerService } from '@nestjs-modules/mailer'
import { Injectable, Logger } from '@nestjs/common'
import { SEND_EMAIL_IN_LOCAL, Stage } from '../../config'
import { SendMailOptions } from './types'

@Injectable()
export class EmailService {
	private readonly logger = new Logger(EmailService.name)

	constructor(private readonly _mailerService: MailerService) {}

	async send(options: SendMailOptions): Promise<void> {
		if (!this.shouldSendEmail()) return

		if (!options.html && (!options.template || !options.context)) {
			this.logger.warn({ message: 'Invalid options provided for email', options })
			return
		}

		const { to, replyTo, subject, from, template, html, context, text, attachments } = options

		await this._mailerService.sendMail({
			to,
			...(replyTo && { replyTo }),
			subject,
			...(from && { from }),
			...(html && { html }),
			...(template && { template, context }),
			...(text && { text }),
			...(attachments && { attachments }),
		})

		this.logger.log({
			message: `Email sent to ${to}`,
			mail: {
				to: options.to,
				replyTo: options.replyTo,
				subject: options.subject,
				template: options.template,
			},
		})
	}

	private shouldSendEmail(): boolean {
		return !(Stage === StageId.LOCAL && !SEND_EMAIL_IN_LOCAL)
	}
}
