import { NextRequest, NextResponse } from "next/server";

const API_URL =
  "https://api.astrology.togwe.com/api/astrologer/review-reply";

export async function POST(request: NextRequest) {
  try {
    const authorization = request.headers.get("authorization");

    if (!authorization) {
      return NextResponse.json(
        {
          status: 401,
          message: "Authorization token is missing.",
        },
        { status: 401 }
      );
    }

    const body = await request.json();

    const reviewId = Number(body?.reviewId);
    const reply =
      typeof body?.reply === "string" ? body.reply.trim() : "";

    // Validate review ID
    if (!Number.isInteger(reviewId) || reviewId <= 0) {
      return NextResponse.json(
        {
          status: 400,
          message: "A valid review ID is required.",
        },
        { status: 400 }
      );
    }

    // Validate reply
    if (!reply) {
      return NextResponse.json(
        {
          status: 400,
          message: "Reply is required.",
        },
        { status: 400 }
      );
    }

    if (reply.length > 1000) {
      return NextResponse.json(
        {
          status: 400,
          message: "Reply cannot exceed 1000 characters.",
        },
        { status: 400 }
      );
    }

    // Debug request without exposing the token

    // Forward request to the backend
    const response = await fetch(API_URL, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
        Authorization: authorization,
      },
      body: JSON.stringify({
        reviewId,
        reply,
      }),
      cache: "no-store",
    });

    const responseText = await response.text();


    let data: any;

    try {
      data = responseText ? JSON.parse(responseText) : {};
    } catch {
      data = {
        message: responseText || "Invalid backend response.",
      };
    }

    return NextResponse.json(data, {
      status: response.status,
    });
  } catch (error) {
    console.error("Review reply proxy error:", error);

    return NextResponse.json(
      {
        status: 500,
        message:
          error instanceof Error
            ? error.message
            : "Unexpected server error.",
      },
      { status: 500 }
    );
  }
}