import { NextResponse, type NextRequest } from 'next/server'; import { physicalCheckoutEnabled } from '@/app/lib/free-studio-checkout'; import { commerceDb, sweepD1AbandonedCheckouts } from '@/app/lib/commerce-db'; import { sendEmail } from '@/app/lib/email'; import { env } from '@/app/lib/env'; import { cartReminderHtml } from '@/app/lib/order-emails'; import { displayOrderId } from '@/app/lib/orders'; export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; // The cart-reminder scheduler calls this every 15 minutes with its bearer secret. // // Two-touch sequence, anchored on cart creation time: // touch 1 — ~1h after the cart was created (cart_reminders_sent 0 → 1) // touch 2 — ~24h after (cart_reminders_sent 1 → 2), the final nudge // Only pending_payment carts are eligible; once paid (→ pending_design) // or swept to abandoned at seven days, they drop out. We also // never chase carts older than that 7-day window. const TOUCH1_AFTER_MS = 60 * 60 * 1000; // 1 hour const TOUCH2_AFTER_MS = 24 * 60 * 60 * 1000; // 24 hours const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; // matches sweep_abandoned_checkouts type CartRow = { id: string; user_email: string | null; config: { styleId?: string; productId?: string; size?: string } | null; cart_reminders_sent: number; created_at: string; }; function summaryOf(config: CartRow['config']): string | null { const c = config ?? {}; const parts = [c.styleId, c.productId, c.size].filter(Boolean); return parts.length ? parts.join(' · ') : null; } export async function GET(req: NextRequest) { if (!physicalCheckoutEnabled()) { return NextResponse.json({ ok: true, skipped: true, considered: 0, due: 0, sent: 0, failed: 0 }); } // Only the scheduler may trigger reminder delivery. if (req.headers.get('authorization') !== `Bearer ${env.cron.secret()}`) { return NextResponse.json({ error: 'unauthorized' }, { status: 401 }); } const admin = commerceDb(); const now = Date.now(); const maxAgeIso = new Date(now - MAX_AGE_MS).toISOString(); await sweepD1AbandonedCheckouts(maxAgeIso); const { data, error } = await admin .from('orders') .select('id, user_email, config, cart_reminders_sent, created_at') .eq('status', 'pending_payment') .lt('cart_reminders_sent', 2) .gt('created_at', maxAgeIso) .order('created_at', { ascending: true }) .limit(100); if (error) { return NextResponse.json({ error: error.message }, { status: 500 }); } const rows = (data ?? []) as CartRow[]; const due = rows.filter((o) => { if (!o.user_email || !o.user_email.includes('@')) return false; const ageMs = now - new Date(o.created_at).getTime(); if (o.cart_reminders_sent === 0) return ageMs >= TOUCH1_AFTER_MS; if (o.cart_reminders_sent === 1) return ageMs >= TOUCH2_AFTER_MS; return false; }); const results = await Promise.allSettled( due.map(async (o) => { const finalTouch = o.cart_reminders_sent === 1; // Claim the reminder before sending. A concurrent tick or a cart // paid since the SELECT returns no row and must not send an email. const { data: claimed, error: bumpErr } = await admin .from('orders') .update({ cart_reminders_sent: o.cart_reminders_sent + 1 }) .eq('id', o.id) .eq('status', 'pending_payment') .eq('cart_reminders_sent', o.cart_reminders_sent) .select('id') .maybeSingle(); if (bumpErr) throw new Error(`bump failed for ${o.id}: ${bumpErr.message}`); if (!claimed) return false; const resumeUrl = `${env.site.url()}/checkout?orderId=${o.id}&resume=1`; await sendEmail({ to: o.user_email!, subject: finalTouch ? 'Still thinking it over? Your portrait is saved' : 'You left a portrait in your cart', html: cartReminderHtml(o.id, resumeUrl, { summary: summaryOf(o.config), finalTouch }), text: `Your custom pet portrait commission (${displayOrderId(o.id)}) is saved — no charge has been made. Pick up where you left off: ${resumeUrl}`, }); return true; }), ); const sent = results.filter((r) => r.status === 'fulfilled' && r.value).length; return NextResponse.json({ ok: true, considered: rows.length, due: due.length, sent, failed: results.filter((r) => r.status === 'rejected').length, }); }