/**
 * GET /api/memory/blocks?q=&limit=&scope=
 *
 * Lists memory blocks from the active backend (Temper or Local).
 * Powers the Memory drawer in /chat — no editing, just inspection.
 *
 * Query params:
 *   q       — optional search query; routed to store.search() so the
 *             active backend's relevance ranking applies (Temper KG,
 *             LocalMemoryStore LIKE). Omit to list everything.
 *   limit   — cap on rows returned (default 200, max 500)
 *   scope   — 'own' | 'global' | 'both' (default 'both'), forwarded
 *             to listBlocks. Ignored when q is set.
 */

import { NextResponse } from 'next/server';
import { getMemoryStore } from '@/lib/chat/memory-store';

export async function GET(req: Request) {
  const url = new URL(req.url);
  const q = (url.searchParams.get('q') || '').trim();
  const limit = Math.min(500, Math.max(1, Number(url.searchParams.get('limit') || 200)));
  const scopeParam = url.searchParams.get('scope');
  const scope: 'own' | 'global' | 'both' =
    scopeParam === 'own' || scopeParam === 'global' || scopeParam === 'both' ? scopeParam : 'both';

  const store = getMemoryStore();
  if (!store.enabled) {
    return NextResponse.json({ backend: store.kind, enabled: false, blocks: [], hits: [] });
  }

  if (q) {
    // Search path — backend chooses ranking (Temper KG vs Local LIKE).
    // listBlocks is also fetched so the UI can show "all blocks" once
    // the user clears the query without a second roundtrip; capped.
    const [hits, all] = await Promise.allSettled([
      store.search(q, limit),
      store.listBlocks({ scope }),
    ]);
    return NextResponse.json({
      backend: store.kind,
      enabled: true,
      query: q,
      hits: hits.status === 'fulfilled' ? hits.value : [],
      blocks: all.status === 'fulfilled' ? all.value.slice(0, limit) : [],
    });
  }

  const blocks = await store.listBlocks({ scope });
  return NextResponse.json({
    backend: store.kind,
    enabled: true,
    blocks: blocks.slice(0, limit),
    hits: [],
  });
}
