import { NextResponse } from "next/server";
import prisma from "@/lib/prisma";
import { getUserIdFromRequest } from "@/lib/auth";
import { z } from "zod";

const schema = z.object({ code: z.string().min(1) });

export async function POST(req: Request) {
  const userId = getUserIdFromRequest(req);
  if (!userId) return NextResponse.json({ error: "login required" }, { status: 401 });
  const body = await req.json().catch(() => ({}));
  const parsed = schema.safeParse(body);
  if (!parsed.success) return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
  const coupon = await prisma.coupon.findUnique({ where: { code: parsed.data.code } });
  if (!coupon || !coupon.active) return NextResponse.json({ error: "invalid coupon" }, { status: 404 });
  if (coupon.expiresAt && coupon.expiresAt < new Date()) return NextResponse.json({ error: "expired" }, { status: 400 });
  const used = await prisma.couponRedemption.count({ where: { couponId: coupon.id } });
  if (coupon.stock > 0 && used >= coupon.stock) return NextResponse.json({ error: "out of stock" }, { status: 400 });
  const mine = await prisma.couponRedemption.count({ where: { couponId: coupon.id, userId } });
  if (mine >= coupon.maxPerUser) return NextResponse.json({ error: "quota exceeded" }, { status: 400 });
  await prisma.couponRedemption.create({ data: { couponId: coupon.id, userId } });
  return NextResponse.json({ ok: true });
}


