import { createDbService } from '@/server/services/db.js';
import React from 'react';
import { z } from 'zod';
import { sendEmail } from '../../../email/resend.js';
import { captureCaught } from '@/server/observability/capture.server';
import type { OutboxHandler } from '../types.js';

const payloadSchema = z.object({
  purchaseId: z.string(),
  vendorRefundedAgorot: z.number().optional(),
  platformAgorot: z.number().optional(),
  attemptedAt: z.string().optional(),
});

type Payload = z.infer<typeof payloadSchema>;

export const paymentsRefundPartialFailure: OutboxHandler<Payload> = {
  type: 'payments.refund.partial_failure',
  payloadSchema,
  async handle(ctx, payload, event) {
    console.error(
      JSON.stringify({
        event: 'outbox_refund_partial_failure',
        purchaseId: payload.purchaseId,
        vendorRefundedAgorot: payload.vendorRefundedAgorot,
        platformAgorot: payload.platformAgorot,
        attemptedAt: payload.attemptedAt,
        outboxId: event.id,
      }),
    );

    if (!ctx.RESEND_API_KEY) {
      if (ctx.strict !== false)
        throw new Error(
          '[outbox] RESEND_API_KEY not configured for payments.refund.partial_failure',
        );
      console.warn(
        JSON.stringify({
          event: 'outbox_secret_missing',
          secret: 'RESEND_API_KEY',
          outboxId: event.id,
        }),
      );
      return;
    }

    const db = createDbService({ DATABASE_URL: ctx.DATABASE_URL });
    const { getSystemConfig } = await import('../../../db/queries/system-config.js');
    const raw = await getSystemConfig(db, 'support_notification_emails');
    let siteEmails: string[];
    try {
      siteEmails = JSON.parse(raw) as string[];
    } catch (err) {
      captureCaught(err, {
        scope: 'server.workflows.outbox.payments-refund-partial-failure',
        severity: 'warning',
      });
      siteEmails = [];
    }
    if (siteEmails.length === 0 && ctx.RESEND_FROM_EMAIL) siteEmails = [ctx.RESEND_FROM_EMAIL];

    for (const to of siteEmails) {
      await sendEmail(
        { RESEND_API_KEY: ctx.RESEND_API_KEY, RESEND_FROM_EMAIL: ctx.RESEND_FROM_EMAIL ?? '' },
        {
          to,
          subject: `[Multideal] Partial refund failure — purchase ${payload.purchaseId}`,
          react: React.createElement(
            'div',
            null,
            React.createElement(
              'p',
              null,
              `Partial refund failure for purchase ${payload.purchaseId}.`,
            ),
            React.createElement(
              'p',
              null,
              `Vendor leg refunded: ${payload.vendorRefundedAgorot ?? 0} agorot.`,
            ),
            React.createElement(
              'p',
              null,
              `Platform leg failed: ${payload.platformAgorot ?? 0} agorot.`,
            ),
            React.createElement('p', null, `Attempted at: ${payload.attemptedAt ?? ''}`),
            React.createElement(
              'p',
              null,
              'Manual intervention required to reconcile platform charge.',
            ),
          ),
        },
      ).catch((err) => {
        captureCaught(err, {
          scope: 'server.workflows.outbox.payments-refund-partial-failure',
          severity: 'info',
        });
      });
    }
  },
};
