import { NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { auth } from '@/auth'
import { revalidatePath } from 'next/cache'

export async function POST(req: Request) {
  try {
    const session = await auth()
    if (!session?.user?.id) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })

    const body = await req.json()
    const { id, name, data } = body

    if (id) {
      const canvas = await prisma.canvas.update({
        where: { id, userId: session.user.id },
        data: { name, data }
      })
      return NextResponse.json({ success: true, canvas })
    } else {
      const canvas = await prisma.canvas.create({
        data: {
          name,
          data,
          userId: session.user.id
        }
      })
      return NextResponse.json({ success: true, canvas })
    }
  } catch (error) {
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
  }
}
