import { createDbService } from '@/server/services/db.js';
import { z } from 'zod';
import { eq } from 'drizzle-orm';
import { deals } from '../../../db/schema.js';
import { sendPaymentRefund } from '../../../email/send.js';
import { requireDecryptedUserEmail } from '../_helpers/decrypt-email.js';
import type { OutboxHandler } from '../types.js';

const payloadSchema = z.object({
  purchaseId: z.string(),
  userId: z.string().nullable().optional(),
  dealId: z.string(),
  refundAmount: z.string().optional(),
  refundDateIso: z.string().optional(),
});

type Payload = z.infer<typeof payloadSchema>;

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

    if (!payload.userId) {
      console.warn(JSON.stringify({ event: 'outbox_refund_email_no_user', outboxId: event.id }));
      return;
    }

    const toEmail = await requireDecryptedUserEmail(ctx, payload.userId, 'refund.executed_email');
    // Documented non-strict missing-PII_KEY skip only; unresolvable recipient throws.
    if (!toEmail) return;

    const db = createDbService({ DATABASE_URL: ctx.DATABASE_URL });
    const dealRows = await db
      .select({ title: deals.title })
      .from(deals)
      .where(eq(deals.id, payload.dealId))
      .limit(1);
    const dealTitle = dealRows[0]?.title ?? '';

    const result = await sendPaymentRefund(
      { RESEND_API_KEY: ctx.RESEND_API_KEY, RESEND_FROM_EMAIL: ctx.RESEND_FROM_EMAIL ?? '' },
      {
        to: toEmail,
        transactionId: payload.purchaseId,
        dealTitle,
        refundAmount: payload.refundAmount ?? '0',
        refundDateIso: payload.refundDateIso ?? new Date().toISOString(),
        paymentMethod: { last4: '****', brand: 'UNKNOWN' },
      },
    );
    if (!result.success) throw new Error(`[outbox] refund email send failed: ${result.error}`);
  },
};
