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

const API_URL =
  "https://api.astrology.togwe.com/api/user/userReview/add";

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();

    console.log(
      "Review proxy request:",
      body
    );

    if (!body?.astrologerId) {
      return NextResponse.json(
        {
          status: 400,
          message: "Astrologer ID is required",
        },
        { status: 400 }
      );
    }

    if (!body?.rating) {
      return NextResponse.json(
        {
          status: 400,
          message: "Rating is required",
        },
        { status: 400 }
      );
    }

    if (!body?.review?.trim()) {
      return NextResponse.json(
        {
          status: 400,
          message: "Review is required",
        },
        { status: 400 }
      );
    }

    /*
     * Get Authorization header from browser
     */
    const authorization =
      request.headers.get("authorization") || "";

    /*
     * Call external Astrology API
     */
    const response = await fetch(API_URL, {
      method: "POST",

      headers: {
        "Content-Type": "application/json",

        ...(authorization
          ? {
              Authorization: authorization,
            }
          : {}),
      },

      body: JSON.stringify({
        astrologerId: Number(
          body.astrologerId
        ),

        rating: Number(body.rating),

        review: String(
          body.review
        ).trim(),

        isPublic:
          body.isPublic !== false,
      }),

      cache: "no-store",
    });

    const text = await response.text();

    let data: any;

    try {
      data = JSON.parse(text);
    } catch {
      data = {
        message: text || "Invalid API response",
      };
    }

    console.log(
      "Review API response:",
      response.status,
      data
    );

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

    return NextResponse.json(
      {
        status: 500,
        message:
          error?.message ||
          "Unable to connect to review API",
      },
      {
        status: 500,
      }
    );
  }
}