import type {
  EmailService,
  SendEmailInput,
  SendEmailResult,
} from '@pikku/core/services'
import {
  renderEmailTemplate,
  type EmailTemplateName,
  type RenderEmailInput,
} from '../../.pikku/email/pikku-emails.gen.js'

export class ProjectEmailService implements EmailService {
  constructor(private readonly delegate: EmailService) {}

  async send(input: SendEmailInput): Promise<SendEmailResult> {
    if (!('template' in input) || !input.template) {
      return this.delegate.send(input)
    }

    const rendered = renderEmailTemplate(
      input.template as RenderEmailInput<EmailTemplateName>
    )

    return this.delegate.send({
      to: input.to,
      from: input.from,
      cc: input.cc,
      bcc: input.bcc,
      replyTo: input.replyTo,
      headers: input.headers,
      subject: input.subject || rendered.subject,
      html: rendered.html,
      ...(rendered.text ? { text: rendered.text } : {}),
    })
  }
}
