using Microsoft.Extensions.Logging;

namespace SteUp.Maui.Core.UtilityException;

public static class GlobalExceptionHandler
{
    public static void Register(ILogger logger)
    {
        AppDomain.CurrentDomain.UnhandledException += (_, args) =>
        {
            var ex = args.ExceptionObject as Exception;
            logger.LogCritical(ex, "UnhandledException (AppDomain) — IsTerminating: {t}", args.IsTerminating);
        };

        TaskScheduler.UnobservedTaskException += (_, args) =>
        {
            logger.LogCritical(args.Exception, "UnobservedTaskException");
            args.SetObserved();
        };

#if ANDROID
        Android.Runtime.AndroidEnvironment.UnhandledExceptionRaiser += (_, args) =>
        {
            logger.LogCritical(args.Exception, "Android UnhandledException");
            args.Handled = true;
        };
#endif

#if IOS || MACCATALYST
        ObjCRuntime.Runtime.MarshalManagedException += (_, args) =>
        {
            logger.LogCritical(args.Exception, "iOS MarshalManagedException");
            args.ExceptionMode = ObjCRuntime.MarshalManagedExceptionMode.UnwindNativeCode;
        };
#endif
    }
}