import { NextResponse } from "next/server" import { prisma } from "@/lib/prisma" import type { Category } from "@/lib/types" export async function POST(request: Request) { try { const category: Omit = await request.json() const created = await prisma.category.create({ data: { name: category.name, color: category.color, icon: category.icon, keywords: JSON.stringify(category.keywords), parentId: category.parentId, }, }) return NextResponse.json({ ...created, keywords: JSON.parse(created.keywords), }) } catch (error) { console.error("Error creating category:", error) return NextResponse.json({ error: "Failed to create category" }, { status: 500 }) } } export async function PUT(request: Request) { try { const category: Category = await request.json() const updated = await prisma.category.update({ where: { id: category.id }, data: { name: category.name, color: category.color, icon: category.icon, keywords: JSON.stringify(category.keywords), parentId: category.parentId, }, }) return NextResponse.json({ ...updated, keywords: JSON.parse(updated.keywords), }) } catch (error) { console.error("Error updating category:", error) return NextResponse.json({ error: "Failed to update category" }, { status: 500 }) } } export async function DELETE(request: Request) { try { const { searchParams } = new URL(request.url) const id = searchParams.get("id") if (!id) { return NextResponse.json({ error: "Category ID is required" }, { status: 400 }) } // Remove category from transactions (set to null) await prisma.transaction.updateMany({ where: { categoryId: id }, data: { categoryId: null }, }) await prisma.category.delete({ where: { id }, }) return NextResponse.json({ success: true }) } catch (error) { console.error("Error deleting category:", error) return NextResponse.json({ error: "Failed to delete category" }, { status: 500 }) } }