import { NextResponse } from "next/server"; import { prisma } from "@/lib/prisma"; import { Prisma } from "@prisma/client"; import { requireAdmin } from "@/lib/admin-auth"; import { badRequest, notFound, serverError } from "@/lib/api-error"; export const dynamic = "force-dynamic"; export async function GET(request: Request) { const authError = await requireAdmin(); if (authError) return authError; try { const { searchParams } = new URL(request.url); const page = parseInt(searchParams.get("page") || "1"); const pageSize = parseInt(searchParams.get("pageSize") || "100"); const [tools, total] = await Promise.all([ prisma.tool.findMany({ orderBy: { createdAt: "desc" }, skip: (page - 1) * pageSize, take: pageSize, include: { category: { select: { id: true, name: true, slug: true } }, }, }), prisma.tool.count(), ]); return NextResponse.json({ tools: tools.map((t) => ({ id: t.id, name: t.name, slug: t.slug, categoryId: t.categoryId, description: t.description, logoUrl: t.logoUrl, websiteUrl: t.websiteUrl, pricingModel: t.pricingModel, pricingDetail: t.pricingDetail, features: t.features, tags: t.tags, viewCount: t.viewCount, status: t.status, category: t.category, createdAt: t.createdAt, })), total, page, pageSize, }); } catch (error) { return serverError(error); } } export async function POST(request: Request) { const authError = await requireAdmin(); if (authError) return authError; try { const body = await request.json(); if (!body.name || !body.websiteUrl || !body.categoryId) { return NextResponse.json({ error: "名称、网址、分类ID不能为空" }, { status: 400 }); } const existingCategory = await prisma.category.findUnique({ where: { id: body.categoryId } }); if (!existingCategory) { return NextResponse.json({ error: "分类ID不存在" }, { status: 400 }); } let slug = body.slug || body.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "tool"; const existing = await prisma.tool.findUnique({ where: { slug } }); if (existing) { slug = slug + "-" + Math.floor(Math.random() * 10000); } const tool = await prisma.tool.create({ data: { name: body.name, slug, categoryId: body.categoryId, description: body.description || "", logoUrl: body.logoUrl || null, websiteUrl: body.websiteUrl || "", pricingModel: body.pricingModel || "freemium", pricingDetail: body.pricingDetail || null, features: body.features || null, tags: body.tags || null, status: body.status || "draft", }, }); return NextResponse.json({ tool }, { status: 201 }); } catch (error) { return serverError(error); } }