import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:crypto/crypto.dart';
import 'package:encrypt/encrypt.dart' as enc;

String encryptData(String plainText, String password) {
  final keyBytes = sha256.convert(utf8.encode(password)).bytes;
  final key = enc.Key(Uint8List.fromList(keyBytes));
  
  final ivBytes = sha256.convert(utf8.encode('${password}_iv')).bytes.sublist(0, 16);
  final iv = enc.IV(Uint8List.fromList(ivBytes));
  
  final encrypter = enc.Encrypter(enc.AES(key, mode: enc.AESMode.cbc));
  final encrypted = encrypter.encrypt(plainText, iv: iv);
  return encrypted.base64;
}

String decryptData(String encryptedBase64, String password) {
  final keyBytes = sha256.convert(utf8.encode(password)).bytes;
  final key = enc.Key(Uint8List.fromList(keyBytes));
  
  final ivBytes = sha256.convert(utf8.encode('${password}_iv')).bytes.sublist(0, 16);
  final iv = enc.IV(Uint8List.fromList(ivBytes));
  
  final encrypter = enc.Encrypter(enc.AES(key, mode: enc.AESMode.cbc));
  final decrypted = encrypter.decrypt(enc.Encrypted.fromBase64(encryptedBase64), iv: iv);
  return decrypted;
}

void main() {
  test('AES-256 CBC Encryption and Decryption Round-trip', () {
    const testData = '{"title":"Korea 2024","days":[],"points":[]}';
    const testPass = 'mojeSuperHeslo123!';
    
    final encStr = encryptData(testData, testPass);
    final decStr = decryptData(encStr, testPass);
    
    expect(decStr, equals(testData));
  });
}
