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

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

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 reason = typeof body?.reason === "string" ? body.reason.trim() : "";

    if (!Number.isInteger(astrologerId) || astrologerId <= 0) {
      return NextResponse.json({ status: 400, message: "A valid astrologerId is required." }, { status: 400 });
    }
    if (!reason) {
      return NextResponse.json({ status: 400, message: "Reason is required." }, { status: 400 });
    }
    if (reason.length > 1000) {
      return NextResponse.json({ status: 400, message: "Reason cannot exceed 1000 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, reason }),
      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("Block astrologer proxy error:", error);
    return NextResponse.json({ status: 500, message: error instanceof Error ? error.message : "Unexpected server error." }, { status: 500 });
  }
}
