import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";

import { EmailService } from "@bff/infra/email/email.service.js";

type OtpEmailContext = "login" | "verification";

/** Template config keys and email subjects per context */
const OTP_EMAIL_CONFIG: Record<
  OtpEmailContext,
  { configKey: string; subject: string; fallbackWarning: string }
> = {
  login: {
    configKey: "EMAIL_TEMPLATE_LOGIN_OTP",
    subject: "Your login verification code",
    fallbackWarning: "If you didn't attempt to log in, please secure your account immediately.",
  },
  verification: {
    configKey: "EMAIL_TEMPLATE_OTP_VERIFICATION",
    subject: "Your verification code",
    fallbackWarning: "If you didn't request this code, please ignore this email.",
  },
};

@Injectable()
export class OtpEmailService {
  constructor(
    private readonly config: ConfigService,
    private readonly emailService: EmailService
  ) {}

  async sendOtpCode(email: string, code: string, context: OtpEmailContext): Promise<void> {
    const { configKey, subject, fallbackWarning } = OTP_EMAIL_CONFIG[context];
    const templateId = this.config.get<string>(configKey);

    if (templateId) {
      await this.emailService.sendEmail({
        to: email,
        subject,
        templateId,
        dynamicTemplateData: { code, expiresMinutes: "10" },
      });
    } else {
      await this.emailService.sendEmail({
        to: email,
        subject,
        html: `
          <p>Your verification code is: <strong>${code}</strong></p>
          <p>This code expires in 10 minutes.</p>
          <p>${fallbackWarning}</p>
        `,
      });
    }
  }
}
