/**
 * Locale-aware email sender — system-communications-notifications.
 *
 * Resolves locale from tenant settings when not provided.
 * IL-first: defaults to 'he-IL' (Hebrew), never hard-codes 'en-US' as fallback.
 */
import { createMail, type MailMessage, type MailResult } from '@platform-modules/mail'
import { makeResendAdapter } from '@platform-modules/mail/resend'
import type { SendEmailOptions } from '@zync/types'
import type { Env } from '@zync/types'
import { renderEmailTemplate } from './render'

/** Resolve locale from tenant settings; IL-first → Hebrew fallback */
function resolveLocale(
  provided: 'he-IL' | 'en-US' | undefined,
  tenantLocale: string | undefined,
): 'he-IL' | 'en-US' {
  if (provided) return provided
  if (tenantLocale === 'en' || tenantLocale === 'en-US') return 'en-US'
  // IL-first default: Hebrew
  return 'he-IL'
}

export function buildMailMessage(opts: SendEmailOptions): MailMessage {
  const locale = resolveLocale(opts.locale, opts.vars['tenantLocale'])
  const { html, text } = renderEmailTemplate({
    templateKey: opts.templateKey,
    vars: opts.vars,
    locale,
  })

  return {
    from: 'Zync <noreply@zync.is>',
    to: opts.to,
    subject: opts.vars['subject'] ?? opts.templateKey,
    html,
    text,
    tags: opts.tags,
  }
}

function createResendMail(env: Pick<Env, 'RESEND_API_KEY'>) {
  return createMail(
    makeResendAdapter({
      apiKey: env.RESEND_API_KEY,
    }),
  )
}

/**
 * Send an email using Resend with locale-aware template rendering.
 * The caller provides `opts.locale`; if omitted, it defaults to the tenant
 * locale from `opts.vars.tenantLocale` or falls back to `he-IL`.
 */
export async function sendEmail(opts: SendEmailOptions, env: Env): Promise<MailResult> {
  return createResendMail(env).send(buildMailMessage(opts))
}
