import React from 'react';
import { z } from 'zod';
import { sendEmail } from '../../../email/resend.js';
import { requireDecryptedVendorEmail } from '../_helpers/decrypt-email.js';
import type { OutboxHandler } from '../types.js';
import { he } from '@/lib/i18n/he';

const payloadSchema = z.object({
  vendorId: z.string(),
});

type Payload = z.infer<typeof payloadSchema>;

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

    const toEmail = await requireDecryptedVendorEmail(
      ctx,
      payload.vendorId,
      'vendor.stripe.onboarding_invite',
    );
    // Documented non-strict missing-PII_KEY skip only; unresolvable recipient throws.
    if (!toEmail) return;

    const result = await sendEmail(
      { RESEND_API_KEY: ctx.RESEND_API_KEY, RESEND_FROM_EMAIL: ctx.RESEND_FROM_EMAIL ?? '' },
      {
        to: toEmail,
        subject: he.vendor_welcome.stripe_invite_subject,
        react: React.createElement(
          'div',
          null,
          React.createElement('p', null, he.vendor_welcome.stripe_invite_body_approved),
          React.createElement('p', null, he.vendor_welcome.stripe_invite_body_complete),
          React.createElement(
            'p',
            null,
            React.createElement(
              'a',
              { href: 'https://dev.multi.deal/vendor/onboarding' },
              he.vendor_welcome.stripe_invite_cta,
            ),
          ),
        ),
      },
    );
    if (!result.success)
      throw new Error(`[outbox] vendor onboarding invite email failed: ${result.error}`);
  },
};
