import { NativeModules, Platform } from 'react-native';

export type BLEDevice = {
  name: string;
  address: string;
  weight: number;
  impedance: number;
};

type BplScaleModuleType = {
  scanDevices(scanDurationMs: number): Promise<BLEDevice[]>;
};

const { BplScale } = NativeModules as { BplScale: BplScaleModuleType };

/**
 * Scan BLE devices and return weight and impedance.
 * @param scanDurationMs Duration of scan in milliseconds
 * @returns Promise resolving to a list of BLE devices with weight & impedance
 */
export const scanDevices = async (scanDurationMs: number): Promise<BLEDevice[]> => {
  if (Platform.OS !== 'android') {
    throw new Error('BplScale module is only supported on Android.');
  }

  try {
    const devices = await BplScale.scanDevices(scanDurationMs);
    return devices;
  } catch (error) {
    console.error('BLE Scan Error:', error);
    throw error;
  }
};

export default {
  scanDevices,
};
