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

// Confirmed live: /astrologer/consultation/messages/sync exists and
// mirrors the customer-side /user/consultation/messages/sync endpoint
// (same {consultation_id, is_final, messages} body — a probe with an
// empty messages array returned the same "min" validation error the
// customer endpoint would, not a 404/401, proving the route is real).
// The astrologer page used to (wrongly) sync through the CUSTOMER'S
// own syncConsultationMessages()/getAuthToken() — which only worked
// during testing because both tokens happened to sit in the same
// browser's localStorage; on a real separate astrologer device (no
// end-user `token` key at all) that call always silently failed with
// "Please login first", so the astrologer's own messages were never
// durably saved. This proxy + astrologer.ts's own sync function fix
// that by authenticating with astrologerToken like every other
// astrologer-side call.
const API_BASE = "https://api.astrology.togwe.com/api/astrologer/consultation/messages/sync";

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

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

    const body = await request.json();

    const response = await fetch(API_BASE, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
        Authorization: authorization,
      },
      body: JSON.stringify(body),
      cache: "no-store",
    });

    const data = await response.json();

    return NextResponse.json(data, { status: response.status });
  } catch (error) {
    console.error("Astrologer consultation messages/sync proxy error:", error);

    return NextResponse.json(
      { status: false, message: "Unable to connect to the astrologer API." },
      { status: 500 },
    );
  }
}
