/**
 * support.notif.email handler.
 *
 * Payload shape: { to, templateKey, params, locale }
 * Produced by enqueueCaseEmail in support/email/enqueue-case-email.ts
 */
import { z } from 'zod';
import { sendEmail } from '../../../email/resend.js';
import { buildSupportEmail } from '../_helpers/support-email.js';
import type { OutboxHandler } from '../types.js';

const payloadSchema = z.object({
  to: z.email(),
  templateKey: z.string(),
  params: z.record(z.string(), z.string()),
  locale: z.enum(['he', 'en']).default('he'),
});

type Payload = z.infer<typeof payloadSchema>;

export const supportNotifEmail: OutboxHandler<Payload> = {
  type: 'support.notif.email',
  payloadSchema,
  async handle(ctx, payload, event) {
    if (!ctx.RESEND_API_KEY) {
      if (ctx.strict !== false)
        throw new Error('[outbox] RESEND_API_KEY not configured for support.notif.email');
      console.warn(
        JSON.stringify({
          event: 'outbox_secret_missing',
          secret: 'RESEND_API_KEY',
          outboxId: event.id,
        }),
      );
      return;
    }

    const { subject, react } = buildSupportEmail(
      payload.templateKey,
      payload.params,
      payload.locale,
    );
    if (!react) {
      console.warn(
        JSON.stringify({
          event: 'outbox_support_email_unknown_template',
          templateKey: payload.templateKey,
          outboxId: event.id,
        }),
      );
      return;
    }

    const result = await sendEmail(
      { RESEND_API_KEY: ctx.RESEND_API_KEY!, RESEND_FROM_EMAIL: ctx.RESEND_FROM_EMAIL ?? '' },
      { to: payload.to, subject, react },
    );
    if (!result.success) throw new Error(`[outbox] support email send failed: ${result.error}`);
  },
};
