// server/src/lib/notifications/channels/email-channel.js
import { sendNotificationEmail } from '../../email.js'
import {
  renderOrderCreatedEmail,
  renderOrderStatusChangedEmail,
  renderOrderMessageEmail,
  renderPaymentStatusChangedEmail,
  renderAdminOrderCreatedEmail,
  renderAdminNewReviewEmail,
  renderAuthCodeEmail,
  renderDeliveryFeeAdjustedEmail,
} from '../templates/email-templates.js'

const templateRenderers = {
  'order:created': renderOrderCreatedEmail,
  'order:statusChanged': renderOrderStatusChangedEmail,
  'orderMessage:adminReply': renderOrderMessageEmail,
  'payment:statusChanged': renderPaymentStatusChangedEmail,
  'order:created:admin': renderAdminOrderCreatedEmail,
  'orderMessage:sent': renderOrderMessageEmail,
  'review:created': renderAdminNewReviewEmail,
  'auth:codeRequested': renderAuthCodeEmail,
  'order:deliveryFeeAdjusted': renderDeliveryFeeAdjustedEmail,
}

export const emailChannel = {
  name: 'email',

  async send({ recipient, eventType, payload }) {
    const renderer = templateRenderers[eventType]
    if (!renderer) {
      return { success: false, error: `No email template for event: ${eventType}` }
    }

    const { subject, html } = renderer(payload)
    const result = await sendNotificationEmail({ to: recipient, subject, html })
    return result
  },
}
