import { NextRequest, NextResponse } from "next/server";
import { getClientIp } from "@/app/lib/clientIp";

// Confirmed live: the Postman collection's "verify-login-otp" path
// 404s on the real backend — the actual route is "verify-login"
// (no "-otp" suffix). Treat Postman as a starting guess, not ground
// truth, per this repo's established convention.
const API_URL =
  "https://api.astrology.togwe.com/api/astrologer/verify-login";

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

    // Client-sent ip_address is a placeholder (a browser can't know
    // its own public IP) — override it with the real one as seen by
    // this server, when a reverse proxy in front of it has forwarded
    // it.
    const clientIp = getClientIp(request);
    const payload = clientIp ? { ...body, ip_address: clientIp } : body;

    const response = await fetch(API_URL, {
      method: "POST",

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

      body: JSON.stringify(payload),

      cache: "no-store",
    });

    const data = await response.json();

    return NextResponse.json(data, { status: response.status });
  } catch (error) {
    console.error("Astrologer verify-login-otp proxy error:", error);

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