/**
 * Send Review Request API
 * POST - Mark a review request as sent and deliver via email/WhatsApp
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { getEffectiveOwnerId } from "@/lib/utils/organization-data";
import { sendReviewRequest } from "@/lib/services/reviews.service";
import { queueEmail } from "@/lib/queue/email-queue";
import { buildReviewRequestEmailHtml } from "@/lib/email/review-request-email";
import { prisma } from "@/lib/db";
import { logger } from "@/lib/logger";
import { getDataSource } from "@/lib/data-source";

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

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 effectiveUserId = await getEffectiveOwnerId(user.userId);
    const body = await request.json();
    const { requestId } = body;

    if (!requestId || typeof requestId !== "string") {
      return NextResponse.json(
        { success: false, error: "requestId is required" },
        { status: 400 },
      );
    }

    if (getDataSource("reviews") === "convex") {
      try {
        const { convexMutation, convexQuery } = await import(
          "@/lib/convex-client"
        );
        const convexResult = (await convexMutation(
          "reviews/mutations:sendReviewRequest",
          {
            userId: effectiveUserId,
            requestId: requestId as string,
          },
        )) as {
          id: string;
          customerName: string;
          customerEmail?: string;
          customerPhone?: string;
          channel: string;
          token: string;
          language?: string;
        } | null;
        if (convexResult !== null) {
          // Send email if the request has an email address and email channel
          let emailQueued = false;
          if (convexResult.customerEmail && convexResult.channel === "email") {
            try {
              const reviewUrl = `${process.env.NEXT_PUBLIC_APP_URL || "https://mawidi.com"}/${convexResult.language || "en"}/review/${convexResult.token}`;
              const language =
                (convexResult.language as "en" | "ar") || "en";

              // Look up business name: prefer canonical company name, fall back to widget settings
              let businessName: string | undefined;
              try {
                const companyName = await convexQuery(
                  "auth/queries:getCompanyNameByAppUserId",
                  { appUserId: effectiveUserId },
                );
                if (companyName) businessName = String(companyName);
              } catch {
                // Non-critical — fall through to widget settings
              }
              if (!businessName) {
                const widgetSettings = (await convexQuery(
                  "reviews/queries:getWidgetSettings",
                  { userId: effectiveUserId },
                ).catch(() => null)) as {
                  businessName?: string;
                  businessNameAr?: string;
                } | null;
                businessName =
                  (language === "ar"
                    ? widgetSettings?.businessNameAr
                    : widgetSettings?.businessName) || undefined;
              }
              if (!businessName) businessName = "Mawidi";

              const email = buildReviewRequestEmailHtml({
                customerName: convexResult.customerName,
                businessName,
                reviewUrl,
                language,
                isReminder: false,
              });

              await queueEmail({
                to: convexResult.customerEmail,
                subject: email.subject,
                html: email.html,
                text: email.text,
                category: "review_request",
                metadata: { reviewRequestId: String(convexResult.id) },
              });
              emailQueued = true;
            } catch (emailError) {
              log.error("Failed to queue review request email (Convex path)", {
                requestId: String(convexResult.id),
                error:
                  emailError instanceof Error
                    ? emailError.message
                    : "Unknown",
              });
            }
          }

          return NextResponse.json({
            success: true,
            reviewRequest: { id: convexResult.id },
            emailQueued,
          });
        }
      } catch {
        // Fall through to Prisma
      }
    }

    const result = await sendReviewRequest(effectiveUserId, requestId);
    if (!result) {
      return NextResponse.json(
        { success: false, error: "Review request not found" },
        { status: 404 },
      );
    }

    // Deliver via email if the request has an email address
    let emailQueued = false;
    if (result.customerEmail && result.channel === "email") {
      try {
        const reviewUrl = `${process.env.NEXT_PUBLIC_APP_URL || "https://mawidi.com"}/${result.language || "en"}/review/${result.token}`;
        const language = (result.language as "en" | "ar") || "en";

        // Look up business name from widget settings, fall back to generic
        const widgetSettings = await prisma.review_widget_settings
          .findUnique({ where: { userId: effectiveUserId } })
          .catch(() => null);
        const businessName =
          (language === "ar"
            ? widgetSettings?.businessNameAr
            : widgetSettings?.businessName) ?? "Mawidi";

        const email = buildReviewRequestEmailHtml({
          customerName: result.customerName,
          businessName,
          reviewUrl,
          language,
          isReminder: false,
        });

        await queueEmail({
          to: result.customerEmail,
          subject: email.subject,
          html: email.html,
          text: email.text,
          category: "review_request",
          metadata: { reviewRequestId: result.id },
        });
        emailQueued = true;
      } catch (emailError) {
        log.error("Failed to queue review request email", {
          requestId: result.id,
          error: emailError instanceof Error ? emailError.message : "Unknown",
        });
      }
    }

    return NextResponse.json({
      success: true,
      reviewRequest: result,
      emailQueued,
    });
  } catch (error) {
    log.error("Failed to send review request", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
