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'

export const runtime = 'nodejs'

// PATCH /api/thoughts/:id — edit body / tags / pinned / archived.
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: { body?: string; tags?: string[]; pinned?: boolean; archived?: boolean } = {}
  if (typeof body.body === 'string' && body.body.trim()) data.body = body.body.trim()
  if (Array.isArray(body.tags)) data.tags = body.tags.filter((x: unknown) => typeof x === 'string')
  if (typeof body.pinned === 'boolean') data.pinned = body.pinned
  if (typeof body.archived === 'boolean') data.archived = body.archived
  if (Object.keys(data).length === 0) return NextResponse.json({ error: 'nothing to update' }, { status: 400 })

  const target = await db.thought.findFirst({ where: { id, ...visible.thought(session.userId) }, select: { id: true } })
  if (!target) return NextResponse.json({ error: 'not found' }, { status: 404 })
  try {
    const t = await db.thought.update({ where: { id }, data })
    const what = data.archived === true ? 'Archived' : data.body ? 'Edited' : data.pinned !== undefined ? (data.pinned ? 'Pinned' : 'Unpinned') : 'Updated'
    logActivity(session.userId, data.archived === true ? 'thought.archived' : 'thought.updated', `${what} thought: ${t.body.slice(0, 80)}`)
  } catch {
    return NextResponse.json({ error: 'not found' }, { status: 404 })
  }
  return NextResponse.json({ ok: true })
}

// DELETE /api/thoughts/:id
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 target = await db.thought.findFirst({ where: { id, ...owned(session.userId) }, select: { id: true } })
  if (!target) return NextResponse.json({ error: 'not found' }, { status: 404 })
  try {
    const t = await db.thought.delete({ where: { id } })
    logActivity(session.userId, 'thought.deleted', `Deleted thought: ${t.body.slice(0, 80)}`)
  } catch {
    return NextResponse.json({ error: 'not found' }, { status: 404 })
  }
  return NextResponse.json({ ok: true })
}
