import { NextResponse, type NextRequest } from 'next/server'; import { commerceDb } from '@/app/lib/commerce-db'; import { getCustomerUser } from '@/app/lib/lumen-auth'; import { downloadOriginalImage } from '@/app/lib/cf-images'; import { encodePhotoJpeg } from '@/app/lib/image-processing'; export const dynamic = 'force-dynamic'; export const runtime = 'nodejs'; export async function GET(request: NextRequest) { const user = await getCustomerUser(); if (!user) return NextResponse.json({ error: 'Sign in to view your saved photos.' }, { status: 401 }); const admin = commerceDb(); const orderId = request.nextUrl.searchParams.get('order'); if (!orderId) { const { data: orders, error } = await admin.from('orders').select('id, config, pet_photo_urls') .eq('user_id', user.id).eq('status', 'cancelled').order('created_at', { ascending: false }); if (error) return NextResponse.json({ error: 'Could not load saved photos.' }, { status: 500 }); const seen = new Set(); const photos = (orders ?? []).flatMap(order => { const cfg = order.config as { pets?: Array<{ name?: string }> } | null; return (order.pet_photo_urls ?? []).flatMap((source: string, slot: number) => { if (!source || seen.has(source)) return []; seen.add(source); return { orderId: order.id, slot, name: cfg?.pets?.[slot]?.name || '' }; }); }); return NextResponse.json({ photos }, { headers: { 'Cache-Control': 'private, no-store' } }); } const slot = request.nextUrl.searchParams.get('slot'); if (slot !== 'style' && !/^[0-3]$/.test(slot ?? '')) { return NextResponse.json({ error: 'Photo not found.' }, { status: 404 }); } const { data: order } = await admin.from('orders').select('pet_photo_urls, custom_style_url') .eq('id', orderId).eq('user_id', user.id).eq('status', 'cancelled').maybeSingle(); const source = slot === 'style' ? order?.custom_style_url : order?.pet_photo_urls?.[Number(slot)]; if (!source) return NextResponse.json({ error: 'Photo not found.' }, { status: 404 }); try { const edge = request.nextUrl.searchParams.has('thumbnail') ? 240 : 2048; const bytes = await encodePhotoJpeg(await downloadOriginalImage(source), 90, edge); return new Response(new Uint8Array(bytes), { headers: { 'content-type': 'image/jpeg', 'Cache-Control': 'private, no-store' } }); } catch { return NextResponse.json({ error: 'Could not load this photo.' }, { status: 502 }); } }