import { authenticateApiRequest } from '@/lib/api-auth'
import { prisma } from '@/lib/prisma'
import { z } from 'zod'

const bodySchema = z.object({
  title: z.string().min(1, 'Titel is verplicht').max(500),
  description: z.string().max(2000, 'Beschrijving mag maximaal 2000 tekens bevatten').optional(),
  product_id: z.string().min(1, 'Product is verplicht'),
})

export async function POST(request: Request) {
  const auth = await authenticateApiRequest(request)
  if ('error' in auth) {
    return Response.json({ error: auth.error }, { status: auth.status })
  }
  if (auth.isDemo) {
    return Response.json({ error: 'Niet beschikbaar in demo-modus' }, { status: 403 })
  }

  let body: unknown
  try {
    body = await request.json()
  } catch {
    return Response.json({ error: 'Malformed JSON' }, { status: 400 })
  }
  const parsed = bodySchema.safeParse(body)
  if (!parsed.success) {
    return Response.json({ error: parsed.error.flatten() }, { status: 422 })
  }

  const product = await prisma.product.findFirst({
    where: { id: parsed.data.product_id, user_id: auth.userId, archived: false },
  })
  if (!product) {
    return Response.json({ error: 'Product niet gevonden' }, { status: 404 })
  }

  const description = parsed.data.description?.trim() || null

  const todo = await prisma.todo.create({
    data: {
      user_id: auth.userId,
      product_id: parsed.data.product_id,
      title: parsed.data.title,
      description,
    },
  })

  return Response.json(
    { id: todo.id, title: todo.title, description: todo.description, created_at: todo.created_at },
    { status: 201 },
  )
}
