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

const API_URL =
  "https://api.astrology.togwe.com/api/astrologer/profile/update-image";

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

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

    const incomingForm = await request.formData();

    const file = incomingForm.get("profile_image");

    if (!file) {
      return NextResponse.json(
        { status: false, message: "No image file provided." },
        { status: 400 },
      );
    }

    const forwardForm = new FormData();

    forwardForm.append("profile_image", file);

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

      headers: {
        Authorization: authorization,
      },

      body: forwardForm,

      cache: "no-store",
    });

    const contentType = response.headers.get("content-type") || "";

    const data = contentType.includes("application/json")
      ? await response.json()
      : await response.text();

    return NextResponse.json(
      typeof data === "string" ? { status: false, message: data } : data,
      { status: response.status },
    );
  } catch (error) {
    console.error("Astrologer update image proxy error:", error);

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