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

export async function GET() {
  const now = new Date();
  const coupons = await prisma.coupon.findMany({
    where: { active: true, OR: [{ expiresAt: null }, { expiresAt: { gte: now } }] },
    orderBy: { createdAt: "desc" },
    select: { id: true, code: true, title: true, description: true, stock: true, maxPerUser: true, expiresAt: true },
  });
  // 사용량 계산
  const ids = coupons.map((c) => c.id);
  const agg = await prisma.couponRedemption.groupBy({ by: ["couponId"], where: { couponId: { in: ids } }, _count: { couponId: true } });
  const usedMap = new Map(agg.map((a) => [a.couponId, a._count.couponId]));
  const items = coupons.map((c) => ({ ...c, used: usedMap.get(c.id) ?? 0 }));
  return NextResponse.json({ coupons: items });
}

const createSchema = z.object({
  code: z.string().min(1),
  title: z.string().min(1),
  description: z.string().optional(),
  stock: z.coerce.number().int().min(0).default(0),
  maxPerUser: z.coerce.number().int().min(1).default(1),
  expiresAt: z.coerce.date().optional(),
});

export async function POST(req: Request) {
  const body = await req.json().catch(() => ({}));
  const parsed = createSchema.safeParse(body);
  if (!parsed.success) return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
  const data = await prisma.coupon.create({ data: parsed.data });
  return NextResponse.json({ coupon: data }, { status: 201 });
}


