/**
 * Review Response API
 * POST - Submit an owner response to a customer review
 *
 * All data access goes through Convex. No Prisma fallback.
 */

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 { queueEmail } from "@/lib/queue/email-queue";
import { logger } from "@/lib/logger";
import { convexMutation, convexQuery } from "@/lib/convex-client";

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

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 { reviewId, response: responseText } = body;

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

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

    const result = await convexMutation("reviews/mutations:updateReview", {
      userId: effectiveUserId,
      reviewId,
      responseText: responseText.trim(),
    });

    if (!result) {
      return NextResponse.json(
        { success: false, error: "Failed to save response" },
        { status: 503 },
      );
    }

    // Send email notification to the customer (non-blocking)
    try {
      const review = (await convexQuery("reviews/queries:getReviewById", {
        userId: effectiveUserId,
        reviewId,
      })) as Record<string, unknown> | null;

      const customerEmail = review?.customerEmail as string | undefined;
      const customerName = (review?.customerName as string) || "Customer";

      if (customerEmail) {
        // Resolve business name
        let businessName = "Mawidi";
        try {
          const companyName = await convexQuery(
            "auth/queries:getCompanyNameByAppUserId",
            { appUserId: effectiveUserId },
          );
          if (companyName) businessName = String(companyName);
        } catch {
          // non-critical
        }
        if (businessName === "Mawidi") {
          const ws = (await convexQuery(
            "reviews/queries:getWidgetSettings",
            { userId: effectiveUserId },
          ).catch(() => null)) as { businessName?: string } | null;
          if (ws?.businessName) businessName = ws.businessName;
        }

        const html = buildReplyEmailHtml({
          customerName,
          businessName,
          responseText: responseText.trim(),
        });

        await queueEmail({
          to: customerEmail,
          subject: `${businessName} responded to your review`,
          html: html,
          text: `Hi ${customerName},\n\n${businessName} replied to your review:\n\n"${responseText.trim()}"\n\nThank you for your feedback!`,
          category: "review_response",
          metadata: { reviewId },
        });

        log.info("Review response email sent", {
          reviewId,
          to: customerEmail,
        });
      }
    } catch (emailErr) {
      log.error(
        "Non-critical: failed to send review response email",
        emailErr instanceof Error ? emailErr : undefined,
      );
    }

    return NextResponse.json({ success: true });
  } catch (error) {
    log.error(
      "Failed to respond to review",
      error instanceof Error ? error : undefined,
    );
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}

function escapeHtml(str: string): string {
  return str
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");
}

function buildReplyEmailHtml({
  customerName,
  businessName,
  responseText,
}: {
  customerName: string;
  businessName: string;
  responseText: string;
}) {
  const safeName = escapeHtml(customerName);
  const safeBiz = escapeHtml(businessName);
  const safeResponse = escapeHtml(responseText);

  return `<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /></head>
<body style="margin:0;padding:0;background-color:#f4f4f5;font-family:Arial,Helvetica,sans-serif;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#f4f4f5;">
    <tr>
      <td align="center" style="padding:32px 16px;">
        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:560px;background-color:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 1px 3px rgba(0,0,0,0.1);">
          <tr>
            <td style="background-color:#10b981;padding:24px 32px;text-align:center;">
              <h1 style="margin:0;color:#ffffff;font-size:22px;font-weight:700;">${safeBiz}</h1>
            </td>
          </tr>
          <tr>
            <td style="padding:32px;">
              <p style="margin:0 0 16px;color:#1e293b;font-size:16px;">Hi ${safeName},</p>
              <p style="margin:0 0 24px;color:#475569;font-size:15px;line-height:1.6;">
                ${safeBiz} has responded to your review:
              </p>
              <div style="background-color:#f0fdf4;border-left:4px solid #10b981;padding:16px;border-radius:8px;margin:0 0 24px;">
                <p style="margin:0;color:#1e293b;font-size:15px;line-height:1.6;font-style:italic;">
                  &ldquo;${safeResponse}&rdquo;
                </p>
              </div>
              <p style="margin:0;color:#94a3b8;font-size:13px;">Thank you for sharing your feedback with us.</p>
            </td>
          </tr>
          <tr>
            <td style="padding:16px 32px;background-color:#f8fafc;text-align:center;border-top:1px solid #e2e8f0;">
              <p style="margin:0;color:#94a3b8;font-size:12px;">&copy; ${new Date().getFullYear()} Mawidi</p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`;
}
