import '../../constant/box_name.dart';
import '../../constant/links.dart';
import '../../main.dart';
import 'crud.dart';

addError1(String error, String details, String where) async {
  try {
    // Get user information for the error log
    final userId = box.read(BoxName.driverID) ?? box.read(BoxName.passengerID);
    final userType =
        box.read(BoxName.driverID) != null ? 'Driver' : 'passenger';
    final phone = box.read(BoxName.phone) ?? box.read(BoxName.phoneDriver);

    // Send the error data to the server
    // Note: This is a fire-and-forget call. We don't await it or handle its response
    // to prevent an infinite loop if the addError endpoint itself is failing.
    CRUD().post(
      link: AppLink.addError,
      payload: {
        'error': error.toString(),
        'userId': userId.toString(),
        'userType': userType,
        'phone': phone.toString(),
        'device': where, // The location of the error
        'details': details, // The detailed stack trace or context
      },
    );
  } catch (e) {
    // If logging the error itself fails, print to the console to avoid infinite loops.
    print("Failed to log error to server: $e");
  }
}
