// ***********************************************************************
// 
//     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 RoleService(ILogger logger, IHttpContextAccessor httpContextAccessor, ICacheService cacheService,
        IOptions cacheSettings, IMongoDatabase database) : IRoleService
    {
        private readonly CacheSettings _cacheSettings = cacheSettings.Value;
        /// 
        /// Creates a new Role.
        /// 
        /// The Role to be created.
        /// A  representing
        /// the asynchronous execution of the service.
        public async Task CreateRoleService(RoleRequest newRole)
        {
            try
            {
                var entity = newRole.ToAdapter(httpContextAccessor);
                await database.GetCollection(CollectionNames.Role).InsertOneAsync(entity);
                entity.Id = (entity as dynamic ?? "").Id.ToString();
                return entity;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"CreateRoleService: Error in getting data - {ex.Message}");
                throw new Exception(ex.Message, ex);
            }
        }
        /// 
        /// Gets an Role by identifier.
        /// 
        /// The Role identifier.
        /// A  representing
        /// the asynchronous execution of the service.
        public async Task GetRoleByIdService(string id)
        {
            var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetRoleByIdService", 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 role = await database.GetCollection(CollectionNames.Role)
                .Find(filter)
                            .FirstOrDefaultAsync();
                var cacheDuration = CacheHelper.GetCacheDuration(_cacheSettings);
                await cacheService.SetAsync(cacheKey, role, cacheDuration);
                return role;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"GetRoleByIdService: Error in getting data - {ex.Message}");
                throw new Exception(ex.Message, ex);
            }
        }
        /// 
        /// Gets all the roles.
        /// 
        /// A  representing
        /// the asynchronous execution of the service.
        public async Task> GetAllRolesService()
        {
            var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllRolesService");
            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.Role)
                                .Find(filter)
                                .ToListAsync();
                var cacheDuration = CacheHelper.GetCacheDuration(_cacheSettings);
                await cacheService.SetAsync(cacheKey, roles, cacheDuration);
                return roles;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"GetAllRolesService: Error in getting data - {ex.Message}");
                throw new Exception(ex.Message, ex);
            }
        }
        /// 
        /// Changes the status of the role.
        /// 
        /// The role identifier.
        /// The new status of the role.
        /// A  representing
        /// the asynchronous execution of the service.
        public async Task ChangeRoleStatusService(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.Role).UpdateOneAsync(filter, update);
                var updatedRole = await database.GetCollection(CollectionNames.Role)
                                    .Find(filter)
                                    .FirstOrDefaultAsync();
                return updatedRole;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"ChangeRoleStatusService: Error in getting data - {ex.Message}");
                throw new Exception(ex.Message, ex);
            }
        }
        /// 
        /// Updates a Role by id.
        /// 
        /// The Role to be updated.
        /// The Role identifier.
        /// A  representing
        /// the asynchronous execution of the service.
        public async Task UpdateRoleService(RoleAdapter 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.Applications, entity.Applications)
                            .Set(v => v.Modules, entity.Modules)
                            .Set(v => v.Permissions, entity.Permissions)
                            .Set(v => v.Status, entity.Status)
                            .Set(v => v.UpdatedBy, Helper.GetEmail(httpContextAccessor))
                            .Set(v => v.UpdatedAt, DateTime.UtcNow);
                await database.GetCollection(CollectionNames.Role).UpdateOneAsync(filter, update);
                var updatedRole = await database.GetCollection(CollectionNames.Role)
                                    .Find(filter)
                                    .FirstOrDefaultAsync();
                return updatedRole;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"UpdateRoleService: Error in getting data - {ex.Message}");
                throw new Exception(ex.Message, ex);
            }
        }
        /// 
        /// Adds an application to the role's list of applications.
        /// 
        /// The identifier of the role to which the application will be added.
        /// The application enum value to add.
        /// A  representing the asynchronous operation, with the updated role object.
        public async Task AddApplicationToRoleService(string roleId, ApplicationsEnum application)
        {
            try
            {
                var filter = Builders.Filter.Eq("_id", ObjectId.Parse(roleId));
                var update = Builders.Update.AddToSet(r => r.Applications, application);
                await database.GetCollection(CollectionNames.Role).UpdateOneAsync(filter, update);
                var updatedRole = await database.GetCollection(CollectionNames.Role)
                                    .Find(filter)
                                    .FirstOrDefaultAsync();
                return updatedRole;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"AddApplicationToRoleService: Error in getting data - {ex.Message}");
                throw new Exception(ex.Message, ex);
            }
        }
        /// 
        /// Removes an application from the role's list of applications.
        /// 
        /// The identifier of the role from which the application will be removed.
        /// The application enum value to remove.
        /// A  representing the asynchronous operation, with the updated role object.
        public async Task RemoveApplicationFromRoleService(string roleId, ApplicationsEnum application)
        {
            try
            {
                var filter = Builders.Filter.Eq("_id", ObjectId.Parse(roleId));
                var update = Builders.Update.Pull(r => r.Applications, application);
                await database.GetCollection(CollectionNames.Role).UpdateOneAsync(filter, update);
                var updatedRole = await database.GetCollection(CollectionNames.Role)
                                    .Find(filter)
                                    .FirstOrDefaultAsync();
                return updatedRole;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"RemoveApplicationFromRoleService: Error in getting data - {ex.Message}");
                throw new Exception(ex.Message, ex);
            }
        }
    }
}