TypeScriptBusiness logicDifficulty 2/3
// app/api/coupons/redeem/route.ts
import { z } from "zod";
import { getSession } from "@/lib/session";
import { db } from "@/lib/db";
const Body = z.object({ code: z.string().min(4).max(32) });
export async function POST(req: Request) {
const session = await getSession();
if (!session) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
const { code } = Body.parse(await req.json());
const coupon = await db.coupon.findUnique({ where: { code } });
if (!coupon || coupon.redeemed) {
return Response.json({ error: "Invalid coupon" }, { status: 400 });
}
await db.account.update({
where: { id: session.accountId },
data: { balanceMinor: { increment: coupon.valueMinor } },
});
await db.coupon.update({
where: { code },
data: { redeemed: true },
});
return Response.json({ ok: true, creditedMinor: coupon.valueMinor });
}