import * as LocalAuthentication from 'expo-local-authentication';
import * as SecureStore from 'expo-secure-store';

export async function isBiometricsAvailable(): Promise<boolean> {
  const compatible = await LocalAuthentication.hasHardwareAsync();
  const enrolled = await LocalAuthentication.isEnrolledAsync();
  return compatible && enrolled;
}

export async function authenticateWithBiometrics(): Promise<boolean> {
  try {
    const result = await LocalAuthentication.authenticateAsync({
      promptMessage: 'Inicia sesión con biometría',
      cancelLabel: 'Cancelar',
      disableDeviceFallback: false,
    });
    return result.success;
  } catch (error) {
    console.error('Biometric authentication error:', error);
    return false;
  }
}

export async function saveBiometricCredentials(username: string): Promise<void> {
  await SecureStore.setItemAsync('biometric_username', username);
}

export async function getBiometricUsername(): Promise<string | null> {
  return await SecureStore.getItemAsync('biometric_username');
}

export async function clearBiometricCredentials(): Promise<void> {
  await SecureStore.deleteItemAsync('biometric_username');
}