/**
 * Reject Suggested FAQ
 *
 * POST /api/dashboard/suggested-faqs/reject
 *
 * Body: { organizationId, suggestionId }
 *
 * Marks a pending FAQ suggestion as rejected. Does not delete the underlying
 * unanswered question — it can still be re-suggested in the future.
 */

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 { convexMutation } from "@/lib/convex-client";

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

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;
    };

    const { organizationId, suggestionId } = body;

    if (!organizationId || !suggestionId) {
      return NextResponse.json(
        {
          success: false,
          error: "organizationId and suggestionId are 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 },
      );
    }

    await convexMutation("whatsapp/mutations:updateSuggestedFaqStatus", {
      id: suggestionId,
      status: "rejected",
    });

    scopedLogger.info("Suggestion rejected", {
      organizationId,
      suggestionId,
      userId: user.userId,
    });

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