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

const API_URL =
  "https://api.astrology.togwe.com/api/user/follower/update";

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

    const body = await req.json();

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

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

    const text = await response.text();

    let data: any;

    try {
      data = JSON.parse(text);
    } catch {
      return NextResponse.json(
        {
          message: "Invalid response from unfollow API",
          status: 502,
        },
        {
          status: 502,
        }
      );
    }

    return NextResponse.json(data, {
      status: response.status,
    });
  } catch (error) {
    console.error(
      "Unfollow astrologer error:",
      error
    );

    return NextResponse.json(
      {
        message: "Server Error",
        status: 500,
      },
      {
        status: 500,
      }
    );
  }
}