/**
 * Knowledge Base Main API
 * GET - Get settings and stats
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { KnowledgeBaseService } from "@/lib/services/knowledge-base.service";
import { logger } from "@/lib/logger";

const scopedLogger = logger.scope("KnowledgeBaseAPI");

/**
 * GET /api/dashboard/knowledge-base
 * Returns settings and stats for the user's knowledge base
 */
export async function GET(request: NextRequest) {
  try {
    const user = await getAuthenticatedUser(request, auth);

    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const [settings, stats] = await Promise.all([
      KnowledgeBaseService.getOrCreateSettings(user.userId),
      KnowledgeBaseService.getStats(user.userId),
    ]);

    scopedLogger.info("Knowledge base overview retrieved", {
      userId: user.userId,
    });

    return NextResponse.json({
      success: true,
      settings,
      stats,
    });
  } catch (error) {
    scopedLogger.error("Failed to get knowledge base overview", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
