// ***********************************************************************
// 
//     AgileWebs
// 
// ***********************************************************************
using Core.Cerberos.Adapters;
using Core.Cerberos.Adapters.Common.Constants;
using Core.Cerberos.Adapters.Common.Enums;
using Core.Cerberos.Domain.Contexts.Onboarding.Mappers;
using Core.Cerberos.Domain.Contexts.Onboarding.Request;
using Core.Cerberos.Infraestructure.Caching.Configs;
using Core.Cerberos.Infraestructure.Caching.Contracts;
using Core.Cerberos.Provider.Contracts;
using LSA.Core.Dapper.Service.Caching;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using MongoDB.Driver;
namespace Core.Cerberos.Provider.Providers.Onboarding
{
    /// 
    /// Handles all services and business rules related to .
    /// 
    public class PermissionService(ILogger logger, IHttpContextAccessor httpContextAccessor, ICacheService cacheService,
        IOptions cacheSettings, IMongoDatabase database) : IPermissionService
    {
        private readonly CacheSettings _cacheSettings = cacheSettings.Value;
        /// 
        /// Creates a new Permission.
        /// 
        /// The Permission to be created.
        /// A  representing
        /// the asynchronous execution of the service.
        public async Task CreatePermissionService(PermissionRequest newPermission)
        {
            try
            {
                var entity = newPermission.ToAdapter(httpContextAccessor);
                await database.GetCollection(CollectionNames.Permission).InsertOneAsync(entity);
                entity.Id = (entity as dynamic ?? "").Id.ToString();
                return entity;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"CreatePermissionService: Error in getting data - {ex.Message}");
                throw new Exception(ex.Message, ex);
            }
        }
        /// 
        /// Gets an Permission by identifier.
        /// 
        /// The Permission identifier.
        /// A  representing
        /// the asynchronous execution of the service.0
        public async Task GetPermissionByIdService(string id)
        {
            var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetPermissionByIdService", id);
            var cachedData = await cacheService.GetAsync(cacheKey);
            if (cachedData is not null) { return cachedData; }
            try
            {
                var filter = Builders.Filter.And(
                    Builders.Filter.Eq("_id", ObjectId.Parse(id)),
                    Builders.Filter.Eq("status", StatusEnum.Active.ToString())
                );
                var permission = await database.GetCollection(CollectionNames.Permission)
                                    .Find(filter)
                                    .FirstOrDefaultAsync();
                var cacheDuration = CacheHelper.GetCacheDuration(_cacheSettings);
                await cacheService.SetAsync(cacheKey, permission, cacheDuration);
                return permission;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"GetPermissionByIdService: Error in getting data - {ex.Message}");
                throw new Exception(ex.Message, ex);
            }
        }
        /// 
        /// Gets all the permissions.
        /// 
        /// A  representing
        /// the asynchronous execution of the service.
        public async Task> GetAllPermissionsService()
        {
            var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllPermissionsService");
            var cachedData = await cacheService.GetAsync>(cacheKey) ?? [];
            if (cachedData.Any()) return cachedData;
            try
            {
                var filter = Builders.Filter.Eq("status", StatusEnum.Active.ToString());
                var roles = await database.GetCollection(CollectionNames.Permission)
                                    .Find(filter)
                                    .ToListAsync();
                var cacheDuration = CacheHelper.GetCacheDuration(_cacheSettings);
                await cacheService.SetAsync(cacheKey, roles, cacheDuration);
                return roles;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"GetAllPermissionsService: Error in getting data - {ex.Message}");
                throw new Exception(ex.Message, ex);
            }
        }
        /// 
        /// Gets all the permissions by permissions identifier list.
        /// 
        /// The list of permissions identifiers.
        /// A  representing
        /// the asynchronous execution of the service.
        public async Task> GetAllPermissionsByListService(string[] permissions)
        {
            var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllPermissionsByListService", permissions);
            var cachedData = await cacheService.GetAsync>(cacheKey);
            if (cachedData != null && cachedData.Any()) return cachedData;
            try
            {
                var objectIds = permissions.Select(id => ObjectId.Parse(id)).ToArray();
                var filter = Builders.Filter.In("_id", objectIds)
                                & Builders.Filter.Eq("status", StatusEnum.Active.ToString());
                var roles = await database.GetCollection(CollectionNames.Permission)
                                          .Find(filter)
                                          .ToListAsync();
                var cacheDuration = CacheHelper.GetCacheDuration(_cacheSettings);
                await cacheService.SetAsync(cacheKey, roles, cacheDuration);
                return roles;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"GetAllPermissionsByListService: Error in getting data - {ex.Message}");
                throw new Exception(ex.Message, ex);
            }
        }
        /// 
        /// Changes the status of the permission.
        /// 
        /// The permission identifier.
        /// The new status of the permission.
        /// A  representing
        /// the asynchronous execution of the service.
        public async Task ChangePermissionStatusService(string id, StatusEnum newStatus)
        {
            try
            {
                var filter = Builders.Filter
                    .Eq("_id", ObjectId.Parse(id));
                var update = Builders.Update
                            .Set(v => v.Status, newStatus)
                            .Set(v => v.UpdatedBy, Helper.GetEmail(httpContextAccessor))
                            .Set(v => v.UpdatedAt, DateTime.UtcNow);
                await database.GetCollection(CollectionNames.Permission).UpdateOneAsync(filter, update);
                var updatedPermission = await database.GetCollection(CollectionNames.Permission)
                                    .Find(filter)
                                    .FirstOrDefaultAsync();
                return updatedPermission;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"ChangePermissionStatusService: Error in getting data - {ex.Message}");
                throw new Exception(ex.Message, ex);
            }
        }
        /// 
        /// Updates a Permission by id.
        /// 
        /// The Permission to be updated.
        /// The Permission identifier.
        /// A  representing
        /// the asynchronous execution of the service.
        public async Task UpdatePermissionService(PermissionAdapter entity, string id)
        {
            try
            {
                var filter = Builders.Filter
                    .Eq("_id", ObjectId.Parse(id));
                var update = Builders.Update
                            .Set(v => v.Name, entity.Name)
                            .Set(v => v.Description, entity.Description)
                            .Set(v => v.AccessLevel, entity.AccessLevel)
                            .Set(v => v.Status, entity.Status)
                            .Set(v => v.UpdatedBy, Helper.GetEmail(httpContextAccessor))
                            .Set(v => v.UpdatedAt, DateTime.UtcNow);
                await database.GetCollection(CollectionNames.Permission).UpdateOneAsync(filter, update);
                var updatedPermission = await database.GetCollection(CollectionNames.Permission)
                                            .Find(filter)
                                            .FirstOrDefaultAsync();
                return updatedPermission;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"UpdatePermissionService: Error in getting data - {ex.Message}");
                throw new Exception(ex.Message, ex);
            }
        }
    }
}