import { NextRequest, NextResponse } from 'next/server'; import { ObjectId } from 'mongodb'; import { getDb } from '@/lib/mongodb'; export async function GET(request: NextRequest) { const { searchParams } = request.nextUrl; const categoryId = searchParams.get('categoryId'); const db = await getDb(); const filter: Record = {}; if (categoryId) { filter.categoryId = new ObjectId(categoryId); } const subcategories = await db.collection('subcategories') .find(filter) .sort({ name: 1 }) .toArray(); return NextResponse.json(subcategories); } export async function POST(request: Request) { const body = await request.json(); const { name, categoryId } = body; if (!name || !categoryId) { return NextResponse.json({ error: 'Name and categoryId are required' }, { status: 400 }); } const db = await getDb(); const now = new Date(); const result = await db.collection('subcategories').insertOne({ name, categoryId: new ObjectId(categoryId), createdAt: now, updatedAt: now, }); return NextResponse.json({ _id: result.insertedId, name, categoryId, createdAt: now, updatedAt: now }, { status: 201 }); }