// FILE: lib/security_service.dart
import 'package:encrypt/encrypt.dart' as encrypt;
import 'dart:convert';
import 'dart:math';

class SecurityService {

  // 1. GENERATORE DI CHIAVI
  static String generaChiaveSessione() {
    const chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890';
    Random rnd = Random.secure();
    return String.fromCharCodes(Iterable.generate(32, (_) => chars.codeUnitAt(rnd.nextInt(chars.length))));
  }

  // 2. CRIPTAZIONE
  static String criptaDati(Map<String, dynamic> dati, String chiaveSegreta) {
    try {
      final key = encrypt.Key.fromUtf8(chiaveSegreta);
      final iv = encrypt.IV.fromLength(16);
      final encrypter = encrypt.Encrypter(encrypt.AES(key));

      String jsonString = jsonEncode(dati);
      final encrypted = encrypter.encrypt(jsonString, iv: iv);

      return "${iv.base64}:${encrypted.base64}";
    } catch (e) {
      return "Errore Criptazione: $e";
    }
  }

  // 3. DECRIPTAZIONE
  static Map<String, dynamic> decriptaDati(String pacchettoCriptato, String chiaveSegreta) {
    try {
      final parts = pacchettoCriptato.split(':');
      if (parts.length != 2) throw Exception("Formato dati non valido");

      final iv = encrypt.IV.fromBase64(parts[0]);
      final encryptedData = encrypt.Encrypted.fromBase64(parts[1]);

      final key = encrypt.Key.fromUtf8(chiaveSegreta);
      final encrypter = encrypt.Encrypter(encrypt.AES(key));

      final decrypted = encrypter.decrypt(encryptedData, iv: iv);
      return jsonDecode(decrypted);
    } catch (e) {
      return {"errore": "Impossibile decriptare: $e"};
    }
  }
}