Branchwell

Lumen & Gesso / website · lumengesso.com / app / api / orders / photos / route.ts

1import { NextResponse, type NextRequest } from 'next/server';
2import { commerceDb } from '@/app/lib/commerce-db';
3import { getCustomerUser } from '@/app/lib/lumen-auth';
4import { downloadOriginalImage } from '@/app/lib/cf-images';
5import { encodePhotoJpeg } from '@/app/lib/image-processing';
6
7export const dynamic = 'force-dynamic';
8export const runtime = 'nodejs';
9
10export async function GET(request: NextRequest) {
11 const user = await getCustomerUser();
12 if (!user) return NextResponse.json({ error: 'Sign in to view your saved photos.' }, { status: 401 });
13 const admin = commerceDb();
14 const orderId = request.nextUrl.searchParams.get('order');
15 if (!orderId) {
16 const { data: orders, error } = await admin.from('orders').select('id, config, pet_photo_urls')
17 .eq('user_id', user.id).eq('status', 'cancelled').order('created_at', { ascending: false });
18 if (error) return NextResponse.json({ error: 'Could not load saved photos.' }, { status: 500 });
19 const seen = new Set<string>();
20 const photos = (orders ?? []).flatMap(order => {
21 const cfg = order.config as { pets?: Array<{ name?: string }> } | null;
22 return (order.pet_photo_urls ?? []).flatMap((source: string, slot: number) => {
23 if (!source || seen.has(source)) return [];
24 seen.add(source);
25 return { orderId: order.id, slot, name: cfg?.pets?.[slot]?.name || '' };
26 });
27 });
28 return NextResponse.json({ photos }, { headers: { 'Cache-Control': 'private, no-store' } });
29 }
30
31 const slot = request.nextUrl.searchParams.get('slot');
32 if (slot !== 'style' && !/^[0-3]$/.test(slot ?? '')) {
33 return NextResponse.json({ error: 'Photo not found.' }, { status: 404 });
34 }
35 const { data: order } = await admin.from('orders').select('pet_photo_urls, custom_style_url')
36 .eq('id', orderId).eq('user_id', user.id).eq('status', 'cancelled').maybeSingle();
37 const source = slot === 'style' ? order?.custom_style_url : order?.pet_photo_urls?.[Number(slot)];
38 if (!source) return NextResponse.json({ error: 'Photo not found.' }, { status: 404 });
39 try {
40 const edge = request.nextUrl.searchParams.has('thumbnail') ? 240 : 2048;
41 const bytes = await encodePhotoJpeg(await downloadOriginalImage(source), 90, edge);
42 return new Response(new Uint8Array(bytes), { headers: { 'content-type': 'image/jpeg', 'Cache-Control': 'private, no-store' } });
43 } catch {
44 return NextResponse.json({ error: 'Could not load this photo.' }, { status: 502 });
45 }
46}