/**
 * AI Question Generation Preview API
 * POST - Generate review questions using AI (preview only, not saved)
 *
 * Automatically detects the user's industry from their company profile.
 * Uses OpenRouter (qwen/qwen3-30b-a3b) to generate industry-specific questions.
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { generateReviewQuestions } from "@/lib/services/review-questions.service";
import { GenerateQuestionsSchema } from "@/lib/validators/reviews.validator";
import { convexQuery } from "@/lib/convex-client";
import { logger } from "@/lib/logger";

const log = logger.scope("ReviewQuestionsGenerateAPI");

interface CompanyProfile {
  _id: string;
  industry: string;
  company_name?: string;
}

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

    const body = await request.json();
    const parsed = GenerateQuestionsSchema.safeParse(body);

    if (!parsed.success) {
      return NextResponse.json(
        { success: false, error: parsed.error.flatten() },
        { status: 400 },
      );
    }

    // Auto-detect industry from company profile if "general" was sent
    let industry = parsed.data.industry;
    if (industry === "general" && user.email) {
      try {
        const profile = await convexQuery<CompanyProfile>(
          "misc/queries:getCompanyProfileByEmail",
          { email: user.email },
        );
        if (profile?.industry) {
          industry = profile.industry;
          log.info("Auto-detected industry from company profile", {
            industry,
            email: user.email,
          });
        }
      } catch {
        log.warn("Could not fetch company profile, using general industry");
      }
    }

    const questions = await generateReviewQuestions(
      industry,
      parsed.data.language,
      parsed.data.count,
    );

    return NextResponse.json({ success: true, questions });
  } catch (error) {
    log.error("Failed to generate review questions", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
