import { NextResponse, type NextRequest } from 'next/server'; import { physicalCheckoutEnabled, physicalCheckoutPausedMessage } from '@/app/lib/free-studio-checkout'; import { commerceDb } from '@/app/lib/commerce-db'; import { provisionCustomer } from '@/app/lib/lumen-auth'; import { uploadImage } from '@/app/lib/cf-images'; import { generateOrderId } from '@/app/lib/orders'; import { priceCents, type ProductId, type Orientation } from '@/app/lib/pricing'; import { validateUpload } from '@/app/lib/upload-limits'; export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; export const maxDuration = 60; type Config = { styleId: string; productId: ProductId; size: string; // Portrait/landscape — persisted via the `...config` spread below and // read back by generation, preview, and Prodigi. Doesn't affect price // (same SKU + tier in both orientations). Optional so legacy orders // without it parse fine. orientation?: Orientation; frame: string; // Mat board colour, or 'nomat' (no mat → Classic Frame fulfilment + // its own lower price). Optional so legacy orders parse; defaults to // the mounted price when absent. matteId?: string; // Edge wrap for the frameless stretched canvas. Optional; ignored by // framed products. wrap?: string; bgColorId: string; bgCustom: string; fontId: string; includeName: boolean; commissionName: string | null; }; export async function POST(req: NextRequest) { if (!physicalCheckoutEnabled()) { return NextResponse.json({ error: physicalCheckoutPausedMessage, studio: '/studio' }, { status: 503, headers: { 'Cache-Control': 'no-store' }, }); } let form: FormData; try { form = await req.formData(); } catch { return NextResponse.json({ error: 'invalid form data' }, { status: 400 }); } const email = String(form.get('email') ?? '').trim().toLowerCase(); const configRaw = String(form.get('config') ?? ''); if (!email || !/.+@.+\..+/.test(email)) { return NextResponse.json({ error: 'valid email required' }, { status: 400 }); } let config: Config; try { config = JSON.parse(configRaw); } catch { return NextResponse.json({ error: 'invalid config json' }, { status: 400 }); } // Collect pet files and names by index. const pets: { name: string; url?: string }[] = []; for (let i = 0; i < 4; i++) { const name = String(form.get(`pet_${i}_name`) ?? '').trim(); const file = form.get(`pet_${i}_file`); if (file instanceof File && file.size > 0) { pets.push({ name }); } else if (name) { pets.push({ name }); } } const customStyleFile = form.get('custom_style_file'); const hasCustomStyle = customStyleFile instanceof File && customStyleFile.size > 0; // Validate every uploaded image (JPG/PNG, ≤10MB) BEFORE creating the // user or uploading anything — never trust the client-side check in // ImageDrop. Fail fast with a 400 listing the offending file. const uploadsToCheck: Array<{ label: string; file: unknown }> = [ { label: 'custom style reference', file: customStyleFile }, ]; for (let i = 0; i < 4; i++) uploadsToCheck.push({ label: `pet photo ${i + 1}`, file: form.get(`pet_${i}_file`) }); for (const { label, file } of uploadsToCheck) { if (file instanceof File && file.size > 0) { const err = validateUpload(file); if (err) { return NextResponse.json({ error: `${label}: ${err}` }, { status: 400 }); } } } let userId: string; try { userId = await provisionCustomer(email); } catch { return NextResponse.json({ error: 'Could not set up the customer account. Please try again.' }, { status: 503 }); } // Upload pet photos to CF Images. Each photo becomes a public URL the // image-gen step (later) and Prodigi (much later) can pull. const photoUrls: string[] = []; try { for (let i = 0; i < 4; i++) { const file = form.get(`pet_${i}_file`); if (!(file instanceof File) || file.size === 0) continue; const { publicUrl } = await uploadImage(file, { filename: file.name, metadata: { kind: 'pet_photo', email, slot: String(i) }, }); photoUrls.push(publicUrl); } } catch (e) { const msg = e instanceof Error ? e.message : String(e); return NextResponse.json({ error: `photo upload failed: ${msg}` }, { status: 500 }); } let customStyleUrl: string | null = null; if (hasCustomStyle && customStyleFile instanceof File) { try { const { publicUrl } = await uploadImage(customStyleFile, { filename: customStyleFile.name, metadata: { kind: 'custom_style', email }, }); customStyleUrl = publicUrl; } catch (e) { const msg = e instanceof Error ? e.message : String(e); return NextResponse.json({ error: `custom style upload failed: ${msg}` }, { status: 500 }); } } const orderId = generateOrderId(); // Sold at cost: the artwork is free, so extra pets and custom style // references don't change the price (see pricing.ts). const cents = priceCents(config.productId, config.size, config.matteId); const { error: insertErr } = await commerceDb().from('orders').insert({ id: orderId, user_id: userId, user_email: email, // Customer pays before we start the design (new flow). The webhook // transitions this to 'pending_design' on checkout.session.completed // and dispatches the magic-link email at that point. status: 'pending_payment', config: { ...config, pets: pets.map((p, i) => ({ slot: i, name: p.name })), hasCustomStyle, }, pet_photo_urls: photoUrls, custom_style_url: customStyleUrl, price_cents: cents, }); if (insertErr) { return NextResponse.json({ error: `order insert failed: ${insertErr.message}` }, { status: 500 }); } // Magic link + welcome emails are deferred to the Stripe webhook — // we only want to email a confirmation once payment succeeds, so the // customer's inbox doesn't fill with "your order is pending" pings // for abandoned checkout sessions. return NextResponse.json({ orderId, email }); }