import { getMdmStatusByUdid } from "../../../db/mdm";
import { requireUser } from "../../../utils/auth";

/**
 * GET /api/magic/mdm/by-udid?udid=...
 *
 * Looks up the NanoMDM enrollment status for an arbitrary UDID. Useful when a
 * USB-connected iPhone has not yet been linked to a ReBreak user device, e.g.
 * to show whether it is already enrolled in ReBreak Cloud.
 */
export default defineEventHandler(async (event) => {
  await requireUser(event);
  const query = getQuery(event);
  const udid = query.udid;

  if (!udid || typeof udid !== "string") {
    throw createError({
      statusCode: 400,
      data: { error: "udid_required" },
    });
  }

  let status: Awaited<ReturnType<typeof getMdmStatusByUdid>>;
  try {
    status = await getMdmStatusByUdid(udid);
  } catch (err: any) {
    console.error("[MDM] NanoMDM DB query failed:", err);
    throw createError({
      statusCode: 503,
      message: "mdm_db_unreachable",
      data: { code: "mdm_db_unreachable" },
    });
  }

  return {
    success: true,
    data: {
      enrolled: status.enrolled,
      company: status.company,
      supervised: status.supervised,
      lastAppPushAt: status.lastAppPushAt?.toISOString() ?? null,
    },
  };
});
