/**
 * Knowledge Base FAQs API
 * GET - List FAQs
 * POST - Create new FAQ
 */

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 { rateLimiters, applyRateLimit } from "@/lib/rate-limiter";
import { logger } from "@/lib/logger";

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

/**
 * GET /api/dashboard/knowledge-base/faqs
 * List all FAQs for the user
 */
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 url = new URL(request.url);
    const category = url.searchParams.get("category") || undefined;
    const activeOnly = url.searchParams.get("activeOnly") !== "false";
    const limit = parseInt(url.searchParams.get("limit") || "100", 10);
    const offset = parseInt(url.searchParams.get("offset") || "0", 10);

    const { faqs, total } = await KnowledgeBaseService.getFAQs(user.userId, {
      category,
      activeOnly,
      limit,
      offset,
    });

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

/**
 * POST /api/dashboard/knowledge-base/faqs
 * Create a new FAQ
 */
export async function POST(request: NextRequest) {
  try {
    // Rate limiting
    const rateLimitResponse = await applyRateLimit(
      request,
      rateLimiters.authGeneral,
    );
    if (rateLimitResponse) {
      return rateLimitResponse;
    }

    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 { questionEn, questionAr, answerEn, answerAr, category, priority } =
      body;

    // Validation
    if (!questionEn || !questionEn.trim()) {
      return NextResponse.json(
        { success: false, error: "Question (English) is required" },
        { status: 400 },
      );
    }

    if (!answerEn || !answerEn.trim()) {
      return NextResponse.json(
        { success: false, error: "Answer (English) is required" },
        { status: 400 },
      );
    }

    const faq = await KnowledgeBaseService.createFAQ(user.userId, {
      questionEn: questionEn.trim(),
      questionAr: questionAr?.trim(),
      answerEn: answerEn.trim(),
      answerAr: answerAr?.trim(),
      category,
      priority,
    });

    scopedLogger.info("FAQ created", { userId: user.userId, faqId: faq.id });

    return NextResponse.json(
      {
        success: true,
        faq,
        message: "FAQ created successfully",
      },
      { status: 201 },
    );
  } catch (error) {
    scopedLogger.error("Failed to create FAQ", error);
    return NextResponse.json(
      { success: false, error: "Failed to create FAQ" },
      { status: 500 },
    );
  }
}
