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'
import { visibleChecklistItemsWhere } from '@/lib/checklist'

export const runtime = 'nodejs'

// GET /api/checklists           — active (non-dismissed) lists with items
// GET /api/checklists?archived=1 — dismissed lists (the reuse history), lighter
export async function GET(req: Request) {
  const session = await getSession()
  if (!session) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })

  const archived = new URL(req.url).searchParams.get('archived') === '1'

  if (archived) {
    const lists = await db.checklist.findMany({
      where: { ...visible.checklist(session.userId), dismissed: true },
      orderBy: { createdAt: 'desc' },
      include: { _count: { select: { items: true } } },
    })
    return NextResponse.json({
      lists: lists.map(l => ({ id: l.id, name: l.name, itemCount: l._count.items, createdAt: l.createdAt })),
    })
  }

  const lists = await db.checklist.findMany({
    where: { ...visible.checklist(session.userId), dismissed: false },
    orderBy: { createdAt: 'desc' },
    include: { items: { where: visibleChecklistItemsWhere(), orderBy: [{ done: 'asc' }, { createdAt: 'asc' }], include: { attachments: { select: { id: true, name: true, thumbPath: true } } } } },
  })
  return NextResponse.json({
    lists: lists.map(l => ({
      id: l.id,
      name: l.name,
      shared: l.visibility === 'HOUSEHOLD',
      items: l.items.map(i => ({ id: i.id, title: i.title, done: i.done, optional: i.optional, topic: i.topic, attachments: i.attachments.map(a => ({ id: a.id, name: a.name, image: !!a.thumbPath })) })),
    })),
  })
}

// POST /api/checklists — create a list ({name}).
export async function POST(req: Request) {
  const session = await getSession()
  if (!session) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })

  const body = await req.json().catch(() => ({}))
  const name = typeof body.name === 'string' ? body.name.trim() : ''
  if (!name) return NextResponse.json({ error: 'name required' }, { status: 400 })

  const list = await db.checklist.create({ data: { name, ownerId: session.userId } })
  logActivity(session.userId, 'list.created', `Created list: ${name}`)
  return NextResponse.json({ id: list.id }, { status: 201 })
}
