import React from 'react';
import { z } from 'zod';
import { sendEmail } from '../../../email/resend.js';
import type { OutboxHandler } from '../types.js';

const payloadSchema = z.object({
  to: z.string(),
  subject: z.string().optional(),
  userId: z.string().optional(),
  message: z.string().optional(),
  subjectLabel: z.string().optional(),
});

type Payload = z.infer<typeof payloadSchema>;

export const contactSupportEmail: OutboxHandler<Payload> = {
  type: 'contact.support_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 contact.support_email');
      console.warn(
        JSON.stringify({
          event: 'outbox_secret_missing',
          secret: 'RESEND_API_KEY',
          outboxId: event.id,
        }),
      );
      return;
    }

    const emailBody = React.createElement(
      'div',
      null,
      React.createElement('p', null, `Subject: ${payload.subjectLabel ?? ''}`),
      React.createElement('p', null, `User ID: ${payload.userId ?? ''}`),
      React.createElement('p', null, 'Message:'),
      React.createElement('pre', { style: { whiteSpace: 'pre-wrap' } }, payload.message ?? ''),
    );

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