export const dynamic = 'force-dynamic'
export const runtime = 'nodejs'

import { NextResponse } from 'next/server'
import { isBearerAuthorized, unauthorized, internalHeaders } from '@/lib/voice-tools'

export async function GET(req: Request) {
  if (!isBearerAuthorized(req)) return unauthorized()

  const baseUrl = `http://localhost:${process.env.PORT || '3000'}`
  const r = await fetch(`${baseUrl}/api/notes`, {
    cache: 'no-store',
    headers: internalHeaders(),
  }).catch(() => null)

  if (!r || !r.ok) return NextResponse.json({ notes: [] }, { status: 502 })
  const j = await r.json()
  // Strip some fields to keep payload small for LLM context
  const notes = (j.notes || []).slice(0, 10).map((n: any) => ({
    id: n.id,
    type: n.type,
    title: n.title,
    pin_date: n.pinDate,
    items: n.type === 'shopping'
      ? (n.items || []).map((i: any) => ({ text: i.text, done: !!i.done }))
      : undefined,
    text: n.type === 'note' ? (n.text || '').slice(0, 500) : undefined,
  }))
  return NextResponse.json({ notes })
}
