/**
 * Native bridge to the Android `DeviceIdentity` Capacitor plugin.
 *
 * On the web (browser preview), this returns an empty MAC so the
 * server falls back to its own pseudo-MAC generation. On Android the
 * plugin returns the most stable identifier the OS allows the app to
 * read (real WiFi MAC if available, otherwise ANDROID_ID formatted
 * as MAC).
 */
import { Capacitor, registerPlugin } from "@capacitor/core";

export interface DeviceIdentity {
  /** "XX:XX:XX:XX:XX:XX" — never empty on Android. */
  mac: string;
  /** "wifi" | "sysfs" | "netif:..." | "android_id" | "fallback" | "web" */
  source: string;
  /** Raw Settings.Secure.ANDROID_ID, only set on Android. */
  android_id?: string;
  model?: string;
  os_version?: string;
}

interface DeviceIdentityPlugin {
  getMac(): Promise<DeviceIdentity>;
}

const Native = registerPlugin<DeviceIdentityPlugin>("DeviceIdentity");

export async function getDeviceIdentity(): Promise<DeviceIdentity> {
  // Web / iOS / etc — no native impl.
  if (Capacitor.getPlatform() !== "android") {
    return { mac: "", source: "web" };
  }
  try {
    return await Native.getMac();
  } catch (e) {
    // Plugin missing or threw — fall back gracefully.
    console.warn("[deviceIdentity] native call failed", e);
    return { mac: "", source: "error" };
  }
}
