import { NextResponse } from "next/server";

const BACKEND_API_URL = "http://134.122.101.22:9000/api/user/account";

export async function POST(request: Request) {
  try {
    const body = await request.json().catch(() => ({}));
    const token = body.token?.trim();

    if (!token) {
      return NextResponse.json(
        { success: false, error: "Missing authentication token. Please open this link directly from the IMZY app." },
        { status: 400 }
      );
    }

    const backendResponse = await fetch(BACKEND_API_URL, {
      method: "DELETE",
      headers: {
        accept: "application/json",
        Authorization: `Bearer ${token}`,
      },
    });

    const data = await backendResponse.json().catch(() => ({}));

    if (!backendResponse.ok) {
      return NextResponse.json(
        {
          success: false,
          error: data.detail || data.message || "Failed to delete account. The token may be invalid or expired.",
        },
        { status: backendResponse.status }
      );
    }

    return NextResponse.json({
      success: true,
      message: data.message || "User account deleted successfully",
    });
  } catch {
    return NextResponse.json(
      { success: false, error: "Unable to reach account service. Please try again later." },
      { status: 502 }
    );
  }
}
