import { NextResponse } from 'next/server'
import { getSession } from '@/lib/auth'
import { db } from '@/lib/db'
import { visible } from '@/lib/scope'
import { thoughtsVersion } from '@/lib/thoughts-version'
import { scheduleOrganize } from '@/lib/agent-trigger'
import { logActivity } from '@/lib/activity'

export const runtime = 'nodejs'

// GET /api/thoughts?q=... — all non-archived thoughts (pinned first), optional
// server-side filter. The thoughts page fetches everything (no q) and searches
// client-side with MiniSearch; q remains for other API consumers.
export async function GET(req: Request) {
  const session = await getSession()
  if (!session) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })

  const q = new URL(req.url).searchParams.get('q')?.trim()
  const [thoughts, topicRows, v] = await Promise.all([
    db.thought.findMany({
      where: {
        AND: [
          visible.thought(session.userId),
          {
            archived: false,
            ...(q ? { OR: [{ body: { contains: q, mode: 'insensitive' } }, { tags: { has: q } }] } : {}),
          },
        ],
      },
      orderBy: [{ pinned: 'desc' }, { createdAt: 'desc' }],
      include: { images: { select: { id: true, name: true, thumbPath: true } } },
    }),
    db.topic.findMany({ where: visible.topic(session.userId), select: { name: true, summary: true } }),
    thoughtsVersion(),
  ])
  const summaries: Record<string, string | null> = {}
  for (const t of topicRows) summaries[t.name] = t.summary
  return NextResponse.json({
    thoughts: thoughts.map(t => ({
      id: t.id, body: t.body, tags: t.tags, topic: t.topic, duplicateOf: t.duplicateOf,
      pinned: t.pinned, createdAt: t.createdAt, sourceId: t.sourceId,
      attachments: t.images.map(a => ({ id: a.id, name: a.name, image: !!a.thumbPath })),
    })),
    topicSummaries: summaries,
    v,
  })
}

// POST /api/thoughts — create a thought directly (typed, no capture).
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 text = (body.body as string)?.trim()
  if (!text) return NextResponse.json({ error: 'body required' }, { status: 400 })
  scheduleOrganize() // new thoughts get a topic without waiting for a manual pass
  logActivity(session.userId, 'thought.created', `Added thought: ${text.slice(0, 80)}`)
  const t = await db.thought.create({
    data: { ownerId: session.userId, body: text, tags: Array.isArray(body.tags) ? body.tags.filter((x: unknown) => typeof x === 'string') : [] },
  })
  return NextResponse.json({ id: t.id })
}
