import { NextResponse } from 'next/server'
import { getSession } from '@/lib/auth'
import { db } from '@/lib/db'
import { visible } from '@/lib/scope'
import { logActivity } from '@/lib/activity'

export const runtime = 'nodejs'

// POST /api/checklists/:id/reuse — clone a list into a fresh active one.
// Copies item titles, optional flag, and AI category; everything starts
// unchecked. Attachments are NOT copied (they're specific to the original).
// Optional body: { name } to override the new list's name.
export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {
  const session = await getSession()
  if (!session) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })

  const { id } = await params
  const src = await db.checklist.findFirst({
    where: { id, ...visible.checklist(session.userId) },
    include: { items: { orderBy: { createdAt: 'asc' } } },
  })
  if (!src) return NextResponse.json({ error: 'not found' }, { status: 404 })

  const body = await req.json().catch(() => ({}))
  const name = (typeof body.name === 'string' && body.name.trim()) || src.name

  const created = await db.checklist.create({
    data: {
      name,
      ownerId: session.userId,
      items: {
        create: src.items.map(i => ({ title: i.title, optional: i.optional, topic: i.topic })),
      },
    },
    select: { id: true },
  })
  logActivity(session.userId, 'list.reused', `Reused list “${src.name}” → new list (${src.items.length} items)`)
  return NextResponse.json({ id: created.id }, { status: 201 })
}
