/**
 * Public Review Submission API (NO AUTH)
 * GET  - Validate token and return questions + widget data
 * POST - Submit a review with question responses
 */

import { NextRequest, NextResponse } from "next/server";
import { submitReviewViaToken } from "@/lib/services/reviews.service";
import { SubmitReviewWithQuestionsSchema } from "@/lib/validators/reviews.validator";
import { logger } from "@/lib/logger";

export const dynamic = "force-dynamic";

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

export async function GET(
  _request: NextRequest,
  { params }: { params: Promise<{ token: string }> },
) {
  try {
    const { token } = await params;
    const { convexQuery } = await import("@/lib/convex-client");

    // Look up review request by token via Convex
    const result = (await convexQuery(
      "reviews/queries:getReviewRequestByToken",
      {
        token,
        statuses: ["PENDING", "SENT"],
        notExpired: true,
      },
    )) as Record<string, unknown> | null;

    if (!result) {
      return NextResponse.json(
        { success: false, error: "Invalid or expired review link" },
        { status: 404 },
      );
    }

    const userId = String(result.userId ?? "");

    // Get widget settings from Convex
    let widgetSettings = null;
    try {
      widgetSettings = await convexQuery(
        "reviews/queries:getWidgetSettings",
        { userId },
      );
    } catch {
      log.warn("Could not load widget settings for public review", { userId });
    }

    // Normalize questions from the request
    let rawQuestions = (result.questions ?? []) as Array<
      Record<string, string>
    >;

    // If no questions on the request, fall back to user's general template
    if (rawQuestions.length === 0) {
      try {
        const template = (await convexQuery(
          "reviews/queries:getQuestionTemplateByIndustry",
          { userId, industry: "general" },
        )) as { questions?: unknown[] } | null;
        if (template?.questions) {
          rawQuestions = (
            template.questions as Array<Record<string, string>>
          ).filter(Boolean);
        }
      } catch {
        // Non-fatal — form will still work with just the overall rating
      }
    }

    const questions = rawQuestions.map((q, i) => ({
      id: q.id || String(i),
      questionEn: q.questionEn || "",
      questionAr: q.questionAr || "",
      type: (q.type as "rating" | "text" | "yesno") || "text",
    }));

    return NextResponse.json({
      success: true,
      customerName: String(result.customerName ?? ""),
      language: String(result.language ?? "en"),
      questions,
      widgetSettings,
    });
  } catch (error) {
    log.error("Failed to validate review token", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ token: string }> },
) {
  // No CSRF check — this is a public endpoint with no auth session.
  // The unique review token is the security mechanism.

  try {
    const { token } = await params;
    const body = await request.json();
    const parsed = SubmitReviewWithQuestionsSchema.safeParse(body);

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

    // submitReviewViaToken creates the review in Convex (including
    // questionResponses) and marks the request as COMPLETED
    const review = await submitReviewViaToken(token, {
      rating: parsed.data.rating,
      title: parsed.data.title ?? null,
      content: parsed.data.content ?? null,
      customerName: parsed.data.customerName,
      language: parsed.data.language,
      questionResponses: parsed.data.questionResponses ?? [],
    });

    if (!review) {
      return NextResponse.json(
        { success: false, error: "Invalid or expired review link" },
        { status: 404 },
      );
    }

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