/**
 * Knowledge Base Single FAQ API
 * GET - Get FAQ details
 * PATCH - Update FAQ
 * DELETE - Delete 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 { logger } from "@/lib/logger";

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

interface RouteParams {
  params: Promise<{ id: string }>;
}

/**
 * GET /api/dashboard/knowledge-base/faqs/[id]
 * Get a single FAQ
 */
export async function GET(request: NextRequest, { params }: RouteParams) {
  try {
    const user = await getAuthenticatedUser(request, auth);

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

    const { id } = await params;
    const faq = await KnowledgeBaseService.getFAQ(user.userId, id);

    if (!faq) {
      return NextResponse.json(
        { success: false, error: "FAQ not found" },
        { status: 404 },
      );
    }

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

/**
 * PATCH /api/dashboard/knowledge-base/faqs/[id]
 * Update FAQ
 */
export async function PATCH(request: NextRequest, { params }: RouteParams) {
  try {
    const user = await getAuthenticatedUser(request, auth);

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

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

    const { id } = await params;
    const body = await request.json();
    const {
      questionEn,
      questionAr,
      answerEn,
      answerAr,
      category,
      priority,
      isActive,
    } = body;

    // Build update data
    const updateData: any = {};
    if (questionEn !== undefined) updateData.questionEn = questionEn.trim();
    if (questionAr !== undefined)
      updateData.questionAr = questionAr?.trim() || null;
    if (answerEn !== undefined) updateData.answerEn = answerEn.trim();
    if (answerAr !== undefined) updateData.answerAr = answerAr?.trim() || null;
    if (category !== undefined) updateData.category = category;
    if (priority !== undefined) updateData.priority = priority;
    if (isActive !== undefined) updateData.isActive = isActive;

    const faq = await KnowledgeBaseService.updateFAQ(
      user.userId,
      id,
      updateData,
    );

    if (!faq) {
      return NextResponse.json(
        { success: false, error: "FAQ not found" },
        { status: 404 },
      );
    }

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

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

/**
 * DELETE /api/dashboard/knowledge-base/faqs/[id]
 * Delete a FAQ
 */
export async function DELETE(request: NextRequest, { params }: RouteParams) {
  try {
    const user = await getAuthenticatedUser(request, auth);

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

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

    const { id } = await params;
    const deleted = await KnowledgeBaseService.deleteFAQ(user.userId, id);

    if (!deleted) {
      return NextResponse.json(
        { success: false, error: "FAQ not found" },
        { status: 404 },
      );
    }

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

    return NextResponse.json({
      success: true,
      message: "FAQ deleted successfully",
    });
  } catch (error) {
    scopedLogger.error("Failed to delete FAQ", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
