import { NextResponse } from "next/server";
import fs from "node:fs";
import path from "node:path";
import { ensureProjectRoot } from "@/lib/paths";
import { requirePageRole } from "@/lib/auth";
import { handleApiError } from "@/lib/api-helpers";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

/** حالة عملية التحديث الجارية — تُقرأ من update-status.json الذي يكتبه apply-update.mjs */
export async function GET() {
  try {
    await requirePageRole("settings", "ADMIN");
    const root = ensureProjectRoot();
    const file = path.join(root, "update-status.json");
    if (!fs.existsSync(file)) {
      return NextResponse.json({ stage: "idle", message: "لا توجد عملية تحديث جارية" });
    }
    const raw = JSON.parse(fs.readFileSync(file, "utf8"));
    return NextResponse.json(raw);
  } catch (err) {
    return handleApiError(err);
  }
}
