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

const API_URL = "https://api.astrology.togwe.com/api/user/astrologer/unblock";

export async function POST(request: NextRequest) {
  try {
    const authorization = request.headers.get("authorization");
    if (!authorization) {
      return NextResponse.json({ status: 401, message: "Authorization token is missing." }, { status: 401 });
    }

    const body = await request.json();
    const astrologerId = Number(body?.astrologerId);
    const remark = typeof body?.remark === "string" ? body.remark.trim() : "";

    if (!Number.isInteger(astrologerId) || astrologerId <= 0) {
      return NextResponse.json({ status: 400, message: "A valid astrologerId is required." }, { status: 400 });
    }
    if (!remark) {
      return NextResponse.json({ status: 400, message: "Remark is required." }, { status: 400 });
    }
    if (remark.length > 500) {
      return NextResponse.json({ status: 400, message: "Remark cannot exceed 500 characters." }, { status: 400 });
    }

    const upstream = await fetch(API_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: authorization },
      body: JSON.stringify({ astrologerId, remark }),
      cache: "no-store",
    });
    const text = await upstream.text();
    let data: unknown;
    try { data = text ? JSON.parse(text) : {}; } catch { data = { message: text }; }
    return NextResponse.json(data, { status: upstream.status });
  } catch (error) {
    console.error("Unblock astrologer proxy error:", error);
    return NextResponse.json({ status: 500, message: error instanceof Error ? error.message : "Unexpected server error." }, { status: 500 });
  }
}
