import { NextResponse } from 'next/server';
import { authSession } from "@/lib/auth/session-server";
import { query } from '@/lib/db-postgres';

export async function GET(
  request: Request,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    const { projectId } = await params;

    const session = await authSession();
    if (!session?.user?.email) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const rows = await query<{ id: string; data: any; created_at: string; updated_at: string }>(
      `SELECT id, data, created_at, updated_at FROM fs_knowledge_items WHERE project_id = $1 ORDER BY created_at DESC LIMIT 100`,
      [projectId]
    );

    const items = rows.map((row) => ({
      id: row.id,
      title: row.data?.title || row.data?.content?.substring(0, 50) || 'Untitled',
      sourceType: row.data?.sourceType,
      content: row.data?.content,
      sourceMeta: row.data?.sourceMeta,
      createdAt: row.created_at,
      updatedAt: row.updated_at,
    }));

    return NextResponse.json({ success: true, items, count: items.length });
  } catch (error) {
    console.error('[API /knowledge/items] Error:', error);
    return NextResponse.json({ success: true, items: [], count: 0 });
  }
}
