3) Order endpoint → Stripe Checkout
// server/routes/domainOrder.ts
import { Router } from "express";
import Stripe from "stripe";
import { v4 as uuid } from "uuid";
import { getRetailPriceForDomain } from "../domains/pricing";
import { saveOrder, getUserIdFromReq } from "../util/store"; // implement save/load
import { z } from "zod";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, { apiVersion: "2024-06-20" });
const router = Router();

const OrderSchema = z.object({
  domain: z.string().min(3),
  years: z.number().int().min(1).max(10).default(1),
  privacy: z.boolean().default(true),
  contact: z.object({
    first: z.string(), last: z.string(), email: z.string().email(),
    phone: z.string(), address1: z.string(), city: z.string(),
    state: z.string(), postal: z.string(), country: z.string().length(2),
    org: z.string().optional(),
  })
});

router.post("/order", async (req, res) => {
  try {
    const body = OrderSchema.parse(req.body);
    const userId = getUserIdFromReq(req) || "anon"; // wire your auth

    // pricing (yours)
    const { priceCents, currency } = getRetailPriceForDomain(body.domain);

    // Create local order row
    const orderId = uuid();
    const order = {
      id: orderId,
      userId,
      domain: body.domain.toLowerCase(),
      years: body.years,
      privacy: body.privacy,
      priceCents,
      currency,
      status: "pending",
      contact: body.contact,
      createdAt: new Date(),
      updatedAt: new Date(),
      provider: "opensrs" as const,
    };
    await saveOrder(order);

    // Stripe Checkout
    const session = await stripe.checkout.sessions.create({
      mode: "payment",
      customer_email: body.contact.email, // or your logged-in user's email
      line_items: [
        {
          quantity: 1,
          price_data: {
            currency,
            unit_amount: priceCents,
            product_data: {
              name: `${body.domain} — ${body.years} year${body.years > 1 ? "s" : ""} registration`,
              description: `WHOIS privacy: ${body.privacy ? "enabled" : "disabled"}`,
            },
          },
        },
      ],
      success_url: `${process.env.APP_BASE_URL}/domains/orders/${orderId}?success=1`,
      cancel_url: `${process.env.APP_BASE_URL}/domains?cancel=1`,
      metadata: {
        orderId,
        domain: body.domain,
        years: String(body.years),
        privacy: String(body.privacy),
      },
    });

    // store session id + move status
    order.status = "checkout_open";
    (order as any).stripeSessionId = session.id;
    await saveOrder(order);

    return res.json({ checkoutUrl: session.url, orderId });
  } catch (e: any) {
    return res.status(400).json({ error: e?.message || "bad request" });
  }
});

export default router;