export const getDeviceId = async () => {
  const existing = localStorage.getItem("guard-device-id");
  if (existing) return existing;

  const fingerprintParts = [
    navigator.userAgent, // Browser and OS
    screen.width + "x" + screen.height, // Screen resolution
    screen.colorDepth, // Color depth
    Intl.DateTimeFormat().resolvedOptions().timeZone, // Time zone
    navigator.platform, // OS platform
    navigator.hardwareConcurrency, // Number of CPU cores
    navigator.language, // Primary language
    navigator.maxTouchPoints, // Touch capability
  ];

  const rawFingerprint = fingerprintParts.join("|");
  const encoder = new TextEncoder();
  const data = encoder.encode(rawFingerprint);

  const hashBuffer = await crypto.subtle.digest("SHA-256", data);
  const hashArray = Array.from(new Uint8Array(hashBuffer));

  const deviceId = hashArray
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("");

  localStorage.setItem("guard-device-id", deviceId);

  return deviceId; // A 64-character hex string
};

export const deriveDeviceKey = async (deviceKeyId: string) => {
  const encoder = new TextEncoder();
  const baseKey = await crypto.subtle.importKey(
    "raw",
    encoder.encode(deviceKeyId),
    { name: "PBKDF2" },
    false,
    ["deriveKey"],
  );
  return crypto.subtle.deriveKey(
    {
      name: "PBKDF2",
      salt: encoder.encode("guard_salt"),
      iterations: 100000,
      hash: "SHA-256",
    },
    baseKey,
    { name: "AES-GCM", length: 256 },
    false,
    ["encrypt", "decrypt"],
  );
};
