import {
  getUserDeviceByDeviceId,
  setUserDeviceMdmId,
} from "../../../../db/mdm";
import { requireUser } from "../../../../utils/auth";

/**
 * Apple UDID: hex/dash, 20–50 chars.
 */
const UDID_RE = /^[A-Fa-f0-9-]{20,50}$/;

/**
 * POST /api/magic/devices/:deviceId/mdm-link
 *
 * Body: { mdmId: string }
 *
 * Links a user's iOS device to a NanoMDM UDID.
 */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const deviceId = getRouterParam(event, "deviceId");
  const body = await readBody(event);
  const mdmId = (body?.mdmId as string | undefined)?.trim();

  if (!deviceId) {
    throw createError({ statusCode: 400, message: "deviceId required" });
  }

  if (!mdmId) {
    throw createError({ statusCode: 400, message: "mdmId required" });
  }

  if (!UDID_RE.test(mdmId)) {
    throw createError({ statusCode: 400, message: "invalid_udid_format" });
  }

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

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

  await setUserDeviceMdmId(user.id, deviceId, mdmId);

  return {
    success: true,
    data: { mdmId },
  };
});
