/**
 * Knowledge Base Settings API
 * GET - Get settings
 * PATCH - Update settings
 */

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 { validateCSRFToken } from "@/lib/csrf";
import { logger } from "@/lib/logger";

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

/**
 * GET /api/dashboard/knowledge-base/settings
 * Returns user's knowledge base settings
 */
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 = await KnowledgeBaseService.getOrCreateSettings(
      user.userId,
    );

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

/**
 * PATCH /api/dashboard/knowledge-base/settings
 * Update knowledge base settings
 */
export async function PATCH(request: NextRequest) {
  try {
    const user = await getAuthenticatedUser(request, auth);

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

    // CSRF protection
    if (!validateCSRFToken(request)) {
      return NextResponse.json(
        { success: false, error: "Invalid CSRF token" },
        { status: 403 },
      );
    }

    const body = await request.json();
    const {
      isEnabled,
      onboardingCompleted,
      maxChunksPerQuery,
      similarityThreshold,
      welcomeMessage,
      customInstructions,
    } = body;

    // Validate numeric fields
    if (
      maxChunksPerQuery !== undefined &&
      (maxChunksPerQuery < 1 || maxChunksPerQuery > 20)
    ) {
      return NextResponse.json(
        { success: false, error: "maxChunksPerQuery must be between 1 and 20" },
        { status: 400 },
      );
    }

    if (
      similarityThreshold !== undefined &&
      (similarityThreshold < 0 || similarityThreshold > 1)
    ) {
      return NextResponse.json(
        {
          success: false,
          error: "similarityThreshold must be between 0 and 1",
        },
        { status: 400 },
      );
    }

    const settings = await KnowledgeBaseService.updateSettings(user.userId, {
      isEnabled,
      onboardingCompleted,
      maxChunksPerQuery,
      similarityThreshold,
      welcomeMessage,
      customInstructions,
    });

    scopedLogger.info("Settings updated", { userId: user.userId });

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