import { NextResponse } from 'next/server'
import { getSession } from '@/lib/auth'
import { db } from '@/lib/db'
import { owned, visible } from '@/lib/scope'
import { logActivity } from '@/lib/activity'
import { scheduleOrganize } from '@/lib/agent-trigger'
import { visibleChecklistItemsWhere } from '@/lib/checklist'

export const runtime = 'nodejs'

// GET /api/checklists/:id — one list with items (the list page).
export async function GET(_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 list = await db.checklist.findFirst({ where: { id, ...visible.checklist(session.userId) }, include: { items: { where: visibleChecklistItemsWhere(), orderBy: [{ done: 'asc' }, { createdAt: 'asc' }], include: { attachments: { select: { id: true, name: true, thumbPath: true } } } } } })
  if (!list) return NextResponse.json({ error: 'not found' }, { status: 404 })
  return NextResponse.json({
    id: list.id, name: list.name, dismissed: list.dismissed, visibility: list.visibility, mine: list.ownerId === session.userId,
    items: list.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 })) })),
  })
}

// PATCH /api/checklists/:id — rename ({name}), dismiss/restore ({dismissed}),
// and/or share with the household ({visibility}).
export async function PATCH(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 body = await req.json().catch(() => ({}))
  const data: { name?: string; dismissed?: boolean; visibility?: 'PRIVATE' | 'HOUSEHOLD' } = {}
  if (typeof body.name === 'string' && body.name.trim()) data.name = body.name.trim()
  if (typeof body.dismissed === 'boolean') data.dismissed = body.dismissed
  if (body.visibility === 'PRIVATE' || body.visibility === 'HOUSEHOLD') data.visibility = body.visibility
  if (Object.keys(data).length === 0) return NextResponse.json({ error: 'nothing to update' }, { status: 400 })

  // Renaming or dismissing a shared list is collaboration; deciding who can
  // see it is not — only the owner may change visibility.
  const scopeFor = data.visibility ? owned(session.userId) : visible.checklist(session.userId)
  const target = await db.checklist.findFirst({ where: { id, ...scopeFor }, select: { id: true } })
  if (!target) return NextResponse.json({ error: 'not found' }, { status: 404 })

  try {
    const l = await db.checklist.update({ where: { id }, data })
    if (data.dismissed === true) logActivity(session.userId, 'list.dismissed', `Dismissed list: ${l.name}`)
    else if (data.dismissed === false) logActivity(session.userId, 'list.restored', `Restored list: ${l.name}`)
    else if (data.name) logActivity(session.userId, 'list.renamed', `Renamed list to: ${l.name}`)
    if (data.visibility) {
      logActivity(session.userId, 'list.visibility',
        data.visibility === 'HOUSEHOLD' ? `Shared list with the household: ${l.name}` : `Made list private: ${l.name}`)
    }
  } catch {
    return NextResponse.json({ error: 'not found' }, { status: 404 })
  }
  return NextResponse.json({ ok: true })
}

// POST /api/checklists/:id — add an item ({title}).
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 body = await req.json().catch(() => ({}))
  const title = typeof body.title === 'string' ? body.title.trim() : ''
  if (!title) return NextResponse.json({ error: 'title required' }, { status: 400 })

  const list = await db.checklist.findFirst({ where: { id, ...visible.checklist(session.userId) }, select: { id: true } })
  if (!list) return NextResponse.json({ error: 'not found' }, { status: 404 })

  const item = await db.checklistItem.create({ data: { listId: id, title } })
  scheduleOrganize() // categorize the new item for the grouped view
  return NextResponse.json({ id: item.id }, { status: 201 })
}

// DELETE /api/checklists/:id — permanently delete a list + its items
// (cascades). Used to prune the archive; dismiss (PATCH) is the soft path.
export async function DELETE(_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 list = await db.checklist.findFirst({ where: { id, ...owned(session.userId) }, select: { name: true } })
  if (!list) return NextResponse.json({ error: 'not found' }, { status: 404 })
  await db.checklist.deleteMany({ where: { id, ...owned(session.userId) } })
  logActivity(session.userId, 'list.deleted', `Permanently deleted list: ${list.name}`)
  return NextResponse.json({ ok: true })
}
