import { createDbService } from '@/server/services/db.js';
import { z } from 'zod';
import { eq } from 'drizzle-orm';
import { deals } from '../../../db/schema.js';
import * as purchaseQueries from '../../../db/queries/purchases.js';
import { sendPurchaseDetails } 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(),
  dealTitle: z.string().optional(),
  qrPngUrl: z.string().optional(),
});

type Payload = z.infer<typeof payloadSchema>;

export const purchaseEmailDetailsQr: OutboxHandler<Payload> = {
  type: 'purchase.email_details_qr',
  payloadSchema,
  async handle(ctx, payload, event) {
    if (!ctx.RESEND_API_KEY) {
      if (ctx.strict !== false) throw new Error('[outbox] RESEND_API_KEY not configured');
      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 purchase = await purchaseQueries.findEnrichedById(db, payload.purchaseId);
    if (!purchase)
      throw new Error(`[outbox] purchase not found for QR email: ${payload.purchaseId}`);

    const [dealRow] = await db
      .select({
        description: deals.description,
        specialInstructions: deals.specialInstructions,
        pickupAddress: deals.pickupAddress,
      })
      .from(deals)
      .where(eq(deals.id, purchase.dealId))
      .limit(1);

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

    const result = await sendPurchaseDetails(
      { RESEND_API_KEY: ctx.RESEND_API_KEY, RESEND_FROM_EMAIL: ctx.RESEND_FROM_EMAIL ?? '' },
      {
        to: toEmail,
        dealTitle: payload.dealTitle ?? purchase.dealTitle ?? '',
        description: dealRow?.description ?? '',
        businessName: purchase.vendorName,
        address: dealRow?.pickupAddress ?? '',
        hours: '',
        qrPngUrl: payload.qrPngUrl ?? purchase.qrPngUrl ?? '',
        expiryIso: purchase.expiresAt.toISOString(),
        specialInstructions: dealRow?.specialInstructions ?? undefined,
      },
    );

    if (!result.success) throw new Error(`[outbox] sendPurchaseDetails failed: ${result.error}`);
  },
};
