import 'package:siro_rider/print.dart';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:crypto/crypto.dart';

Future<bool> verifyCertificateManually(
    String host, int port, String expectedPin) async {
  try {
    final socket = await SecureSocket.connect(host, port,
        timeout: const Duration(seconds: 5));

    final certificate = socket.peerCertificate;
    if (certificate == null) {
      Log.print("❌ لا يوجد شهادة.");
      return false;
    }

    final der = certificate.der;
    final actualPin = base64.encode(sha256.convert(der).bytes);

    Log.print("📛 HOST: $host");
    Log.print("📜 Subject: ${certificate.subject}");
    Log.print("📜 Issuer: ${certificate.issuer}");
    Log.print("📅 Valid From: ${certificate.startValidity}");
    Log.print("📅 Valid To: ${certificate.endValidity}");
    Log.print(
        "🔐 Server Pin: $actualPin → ${actualPin == expectedPin ? '✅ MATCH' : '❌ MISMATCH'}");

    socket.destroy();
    return actualPin == expectedPin;
  } catch (e) {
    Log.print("❌ خطأ أثناء الاتصال أو الفحص: $e");
    return false;
  }
}

/// تحويل المفتاح العام إلى بصمة SHA-256
List<int> sha256Convert(Uint8List der) {
  return sha256.convert(der).bytes;
}