import {
  clearUserDeviceMdmId,
  getMdmStatusByUdid,
  getUserDeviceByDeviceId,
} from "../../../../db/mdm";
import { getDeviceProtectionState } from "../../../../db/device-protection";
import { requireUser } from "../../../../utils/auth";

/**
 * GET /api/magic/devices/:deviceId/mdm
 *
 * Returns the NanoMDM enrollment status for the user's iOS device and the
 * locally tracked nefilter (lock profile) protection state.
 */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const deviceId = getRouterParam(event, "deviceId");

  if (!deviceId) {
    throw createError({
      statusCode: 400,
      data: { error: "device_id_required" },
    });
  }

  const device = await getUserDeviceByDeviceId(user.id, deviceId, "ios");

  if (!device) {
    throw createError({
      statusCode: 404,
      data: { error: "device_not_found" },
    });
  }

  // Not linked to a NanoMDM UDID → enrolled false.
  if (!device.mdmId) {
    return {
      success: true,
      data: {
        enrolled: false,
        company: null,
        supervised: false,
        lockProfileInstalled: false,
        lastAppPushAt: null,
      },
    };
  }

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

  // UDID stored but the device is completely gone from NanoMDM → clear stale link.
  if (!status.exists) {
    await clearUserDeviceMdmId(user.id, deviceId);
    return {
      success: true,
      data: {
        enrolled: false,
        company: null,
        supervised: false,
        lockProfileInstalled: false,
        lastAppPushAt: null,
      },
    };
  }

  // Lock-profile state is derived from the locally tracked nefilter state,
  // not from MDM enrollment alone.
  const lockState = await getDeviceProtectionState(
    user.id,
    deviceId,
    "nefilter",
  );

  return {
    success: true,
    data: {
      enrolled: true,
      company: "ReBreak",
      supervised: status.supervised,
      lockProfileInstalled: lockState?.active ?? false,
      lastAppPushAt: status.lastAppPushAt?.toISOString() ?? null,
    },
  };
});