/**
 * Customer email adapter — customers module.
 *
 * Enqueues typed messages onto the shared QUEUE binding for the communications
 * worker to consume. The function signatures are the stable contract; when
 * `system-communications-notifications` lands it will provide direct Resend
 * integration without changing these signatures.
 */
import type { Env } from '@zync/types'

type CustomerEmailMessage =
  | {
      kind: 'portal_invitation'
      to: string
      token: string
      tenantId: string
      customerId: string
      contactId: string
      invitedBy: string
    }
  | {
      kind: 'customer_email'
      to: string
      subject: string
      body: string
      tenantId: string
      customerId: string
      sentBy: string
    }

async function enqueue(env: Env, msg: CustomerEmailMessage): Promise<void> {
  try {
    await env.QUEUE.send({ type: 'email', ...msg })
  } catch (err) {
    console.error(`[email-customers] failed to enqueue ${msg.kind} for ${msg.to}`, err)
  }
}

/**
 * Send a portal invitation email.
 * Carries PLAINTEXT token; DB stores only the SHA-256 hash.
 * The portal link is /portal/:tenantSlug?token=<plaintext>.
 */
export async function sendPortalInvitationEmail(
  env: Env,
  opts: {
    to: string
    token: string
    tenantId: string
    customerId: string
    contactId: string
    invitedBy: string
  },
): Promise<void> {
  await enqueue(env, {
    kind: 'portal_invitation',
    to: opts.to,
    token: opts.token,
    tenantId: opts.tenantId,
    customerId: opts.customerId,
    contactId: opts.contactId,
    invitedBy: opts.invitedBy,
  })
}

/**
 * Send a staff-composed outbound customer email.
 * `from_address` is resolved by the communications worker from the tenant config.
 */
export async function sendCustomerEmail(
  env: Env,
  opts: {
    to: string
    subject: string
    body: string
    tenantId: string
    customerId: string
    sentBy: string
  },
): Promise<void> {
  await enqueue(env, {
    kind: 'customer_email',
    to: opts.to,
    subject: opts.subject,
    body: opts.body,
    tenantId: opts.tenantId,
    customerId: opts.customerId,
    sentBy: opts.sentBy,
  })
}
