/**
 * Approve Suggested FAQ
 *
 * POST /api/dashboard/suggested-faqs/approve
 *
 * Two modes:
 * 1. { suggestionId } — approves an existing pending suggestion, copies it to KB
 * 2. { questionId, generate: true } — generates a suggestion from an unanswered
 *    question and immediately approves it (one-click flow)
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { validateCSRFToken } from "@/lib/csrf";
import { rateLimiters, applyRateLimit } from "@/lib/rate-limiter";
import { logger } from "@/lib/logger";
import prisma from "@/lib/db";
import { convexQuery, convexMutation } from "@/lib/convex-client";
import { companyKnowledgeBaseAdapter } from "@/lib/adapters/whatsapp";

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

interface SuggestionDoc {
  _id: string;
  organizationId: string;
  question: string;
  suggestedAnswer: string;
  language: string;
  frequency: number;
  status: string;
}

interface UnansweredDoc {
  _id: string;
  organizationId: string;
  question: string;
  language: string;
  frequency: number;
}

async function findSuggestionById(
  organizationId: string,
  suggestionId: string,
): Promise<SuggestionDoc | null> {
  const list = await convexQuery<SuggestionDoc[]>(
    "whatsapp/queries:getSuggestedFaqs",
    { organizationId, limit: 100 },
  ).catch(() => [] as SuggestionDoc[]);
  if (!Array.isArray(list)) return null;
  return list.find((s) => s._id === suggestionId) ?? null;
}

async function findUnansweredById(
  organizationId: string,
  questionId: string,
): Promise<UnansweredDoc | null> {
  const list = await convexQuery<UnansweredDoc[]>(
    "whatsapp/queries:getUnansweredQuestions",
    { organizationId, limit: 100 },
  ).catch(() => [] as UnansweredDoc[]);
  if (!Array.isArray(list)) return null;
  return list.find((q) => q._id === questionId) ?? null;
}

export async function POST(request: NextRequest) {
  try {
    const rateLimitResponse = await applyRateLimit(
      request,
      rateLimiters.authGeneral,
    );
    if (rateLimitResponse) return rateLimitResponse;

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

    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const body = (await request.json()) as {
      organizationId?: string;
      suggestionId?: string;
      questionId?: string;
      generate?: boolean;
    };

    const { organizationId, suggestionId, questionId, generate } = body;

    if (!organizationId) {
      return NextResponse.json(
        { success: false, error: "organizationId is required" },
        { status: 400 },
      );
    }

    // Verify org ownership
    const org = await prisma.organizations.findFirst({
      where: { id: organizationId },
      select: { id: true, ownerId: true },
    });
    if (!org || org.ownerId !== user.userId) {
      return NextResponse.json(
        { success: false, error: "Forbidden" },
        { status: 403 },
      );
    }

    let questionText: string;
    let answerText: string;
    let language: string;

    if (suggestionId && !generate) {
      // Mode 1: approve existing suggestion
      const suggestion = await findSuggestionById(organizationId, suggestionId);
      if (!suggestion) {
        return NextResponse.json(
          { success: false, error: "Suggestion not found" },
          { status: 404 },
        );
      }
      questionText = suggestion.question;
      answerText = suggestion.suggestedAnswer;
      language = suggestion.language;

      // Mark suggestion approved
      await convexMutation(
        "whatsapp/mutations:updateSuggestedFaqStatus",
        {
          id: suggestionId,
          status: "approved",
          approvedBy: user.userId,
        },
      );
    } else if (questionId && generate) {
      // Mode 2: generate from unanswered question and approve
      const question = await findUnansweredById(organizationId, questionId);
      if (!question) {
        return NextResponse.json(
          { success: false, error: "Question not found" },
          { status: 404 },
        );
      }
      questionText = question.question;
      // Template answer — owner can edit later
      answerText =
        question.language === "ar"
          ? "يرجى التواصل معنا للحصول على المزيد من المعلومات."
          : "Please contact us for more information about this inquiry.";
      language = question.language;
    } else {
      return NextResponse.json(
        {
          success: false,
          error: "Either suggestionId or { questionId, generate: true } required",
        },
        { status: 400 },
      );
    }

    // Insert into company knowledge base
    const now = new Date();
    await companyKnowledgeBaseAdapter.create({
      data: {
        organizationId,
        question: questionText,
        answer: answerText,
        category: "approved_suggestion",
        language,
        isActive: true,
        priority: 0,
        createdAt: now,
        updatedAt: now,
      },
    });

    scopedLogger.info("Suggestion approved and added to KB", {
      organizationId,
      suggestionId,
      questionId,
      language,
    });

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