import { Injectable, Logger } from "@nestjs/common"
import { SESClient, SendEmailCommand } from "@aws-sdk/client-ses"

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

  constructor() {
    this.sesClient = new SESClient({
      region: process.env.AWS_REGION || "us-east-1",
      credentials: {
        accessKeyId: process.env.SMTP_AWS_ACCESS_KEY_ID || "",
        secretAccessKey: process.env.SMTP_AWS_SECRET_ACCESS_KEY || "",
      },
    })
  }

  /**
   * Sends an email using AWS SES.
   * @param to Recipient email(s) — single email or array
   * @param subject Email subject line
   * @param body Email body (supports both HTML and plain text)
   * @param cc Optional CC recipient(s)
   * @param bcc Optional BCC recipient(s)
   * @returns Promise resolving with MessageId on success
   */
  async sendEmail(
    to: string | string[],
    subject: string,
    body: { html?: string; text?: string },
    cc?: string | string[],
    bcc?: string | string[],
  ): Promise<string> {
    try {
      if (!to || !subject || (!body.html && !body.text)) {
        throw new Error("Missing required email parameters")
      }
      const destinationTo = Array.isArray(to) ? to : [to]
      const destinationCc = cc ? (Array.isArray(cc) ? cc : [cc]) : undefined
      const destinationBcc = bcc
        ? Array.isArray(bcc)
          ? bcc
          : [bcc]
        : undefined

      const command = new SendEmailCommand({
        Destination: {
          ToAddresses: destinationTo,
          CcAddresses: destinationCc,
          BccAddresses: destinationBcc,
        },
        Message: {
          Body: {
            Html: body.html ? { Data: body.html } : undefined,
            Text: body.text ? { Data: body.text } : undefined,
          },
          Subject: { Data: subject },
        },
        Source: process.env.EMAIL_FROM,
      })

      const response = await this.sesClient.send(command)

      console.log("=".repeat(100))
      console.log("response", response)
      console.log("=".repeat(100))

      this.logger.log(
        `📧 Email sent to ${destinationTo.join(", ")}${
          destinationCc ? ` | CC: ${destinationCc.join(", ")}` : ""
        }${destinationBcc ? ` | BCC: ${destinationBcc.join(", ")}` : ""} | MessageId: ${
          response.MessageId
        }`,
      )
      return response.MessageId ?? ""
    } catch (error) {
      this.logger.error(
        `❌ Failed to send email: ${error.message}`,
        error.stack,
      )
      throw new Error(`Error sending email: ${error.message}`)
    }
  }
}
