import { listUserDevices } from "../../db/devices";
import { getProfile } from "../../db/profile";
import { getPlanLimits } from "../../utils/plan-features";

/**
 * GET /api/devices
 *
 * Liste aller registrierten Devices des Users + plan-limit + welches Device der
 * aktuelle Caller ist (matched via x-device-id header).
 */
export default defineEventHandler(async (event) => {
  // skipDeviceCheck: User der gerade vom Geräte-Limit blockt wird, soll trotzdem
  // seine Devices-Liste sehen können um eines freizugeben (Chicken-Egg-Bypass).
  const user = await requireUser(event, { skipDeviceCheck: true });
  const profile = await getProfile(user.id);
  const limits = getPlanLimits(profile?.plan ?? "free");

  const currentDeviceId = getHeader(event, "x-device-id") ?? null;
  const devices = await listUserDevices(user.id);

  return {
    devices: devices.map((d) => ({
      ...d,
      isCurrent: !!currentDeviceId && d.deviceId === currentDeviceId,
    })),
    max: limits.maxAppDevices,
    plan: profile?.plan ?? "free",
  };
});
