
using Quadarax.Foundation.Core.Business;
using Quadarax.Foundation.Core.Data;
using Quadarax.Foundation.Core.Data.Interface.Repository;
using Quadarax.Foundation.Core.Logging;
using System.Runtime.CompilerServices;
using System.Security.Principal;

namespace qdr.app.bundleboiler.business.Services
{
    public abstract class BaseService<TRepository> : AbstractRepositoryService<TRepository>
        where TRepository : IRepository
    {
        #region *** Properties ***

        protected IOptions Options { get; }
        #endregion

        protected BaseService(TRepository repository, IOptions options, ILogger logger) : base(repository, Thread.CurrentPrincipal ?? new WindowsPrincipal(WindowsIdentity.GetAnonymous()), logger)
        {
            Options = options ?? throw new ArgumentNullException(nameof(options));
        }

        protected TResult Operation<TResult>(Func<TResult> operation, [CallerMemberName] string callerName = "unknown")
            where TResult : IResult
        {
            var result = Result.Ok;
            try
            {

                result = operation();
            }
            catch (Exception ex)
            {
                Log.Log(LogSeverityEnum.Fatal, $"Error during '{callerName}' operation: {ex.Message}", ex);
                result = new Result([new Error(ex)]);
            }

            return (TResult)result;
        }
    }

    public abstract class BaseService : AbstractService
    {
        #region *** Properties ***

        protected IOptions Options { get; }
        #endregion

        protected BaseService(IOptions options, ILogger logger) : base(Thread.CurrentPrincipal ?? new WindowsPrincipal(WindowsIdentity.GetAnonymous()), logger)
        {
            Options = options ?? throw new ArgumentNullException(nameof(options));
        }

        protected TResult Operation<TResult>(Func<TResult> operation, [CallerMemberName] string callerName = "unknown")
    where TResult : IResult
        {
            var result = Result.Ok;
            try
            {

                result = operation();
            }
            catch (Exception ex)
            {
                Log.Log(LogSeverityEnum.Fatal, $"Error during '{callerName}' operation: {ex.Message}", ex);
                result = new Result([new Error(ex)]);
            }

            return (TResult)result;
        }
    }

}
