import { SessionStore } from '@backend/auth'
import { Reservation } from '@backend/domain'
import { SettingsRepository } from '@backend/repository'
import { BadRequestException, Injectable, Logger } from '@nestjs/common'
import { EmailService, MAILER_TEMPLATES, SendMailOptions } from '../../../global'

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

	constructor(
		private readonly _emailService: EmailService,
		private readonly _settingsRepository: SettingsRepository,
	) {}

	/**
	 * Send an email to the customer to collect their feedback
	 */
	async sendFeedbackEmail(reservation: Reservation): Promise<void> {
		if (!reservation.customerData.email) return

		const settings = await this._settingsRepository.findOne({
			select: { customerApp: {}, restaurant: {}, email: {} },
		})
		if (!settings) throw new BadRequestException('Tenant settings not found')

		if (!settings.email?.feedbackContent) {
			this.logger.warn({ message: 'Feedback content not set', tenantId: SessionStore.tenantId })
			return
		}

		const context = {
			restaurant_name: settings.customerApp.displayName,
			restaurant_logo: settings.customerApp.logoUrl,
			feeback_content: settings.email.feedbackContent,
		}

		const email: SendMailOptions = {
			to: reservation.customerData.email,
			replyTo: {
				address: settings.restaurant.email,
				name: settings.customerApp.displayName,
			},
			subject: `Give your feedback for ${settings.customerApp?.displayName}`,
			template: MAILER_TEMPLATES.RESERVATION.FEEDBACK.MINIMAL,
			context,
		}

		await this._emailService.send(email)
	}
}
