// ***********************************************************************
// 
//     AgileWebs
// 
// ***********************************************************************
using Core.Thalos.Adapters;
using Core.Thalos.Adapters.Common.Constants;
using Core.Thalos.Adapters.Common.Enums;
using Core.Thalos.Domain.Contexts.Onboarding.Mappers;
using Core.Thalos.Domain.Contexts.Onboarding.Request;
using Core.Thalos.Infraestructure.Caching.Configs;
using Core.Thalos.Infraestructure.Caching.Contracts;
using Core.Thalos.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.Thalos.Provider.Providers.Onboarding
{
    /// 
    /// Handles all services and business rules related to .
    /// 
    public class ModuleService(ILogger logger, IHttpContextAccessor httpContextAccessor, ICacheService cacheService,
        IOptions cacheSettings, IMongoDatabase database) : IModuleService
    {
        private readonly CacheSettings _cacheSettings = cacheSettings.Value;
        /// 
        /// Creates a new Module.
        /// 
        /// The Module to be created.
        /// A  representing
        /// the asynchronous execution of the service.
        public async Task CreateModuleService(ModuleRequest newModule)
        {
            try
            {
                var entity = newModule.ToAdapter(httpContextAccessor);
                entity.Order = (entity.Order is not null) ? entity.Order : await GetLastOrderModule(newModule);
                await database.GetCollection(CollectionNames.Module).InsertOneAsync(entity);
                entity.Id = (entity as dynamic ?? "").Id.ToString();
                return entity;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"CreateModuleService: Error in getting data - {ex.Message}");
                throw new Exception(ex.Message, ex);
            }
        }
        /// 
        /// Gets an Module by identifier.
        /// 
        /// The Module identifier.
        /// A  representing
        /// the asynchronous execution of the service.0
        public async Task GetModuleByIdService(string id)
        {
            var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetModuleByIdService", 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 module = await database.GetCollection(CollectionNames.Module)
                                    .Find(filter)
                                    .FirstOrDefaultAsync();
                var cacheDuration = CacheHelper.GetCacheDuration(_cacheSettings);
                await cacheService.SetAsync(cacheKey, module, cacheDuration);
                return module;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"GetModuleByIdService: Error in getting data - {ex.Message}");
                throw new Exception(ex.Message, ex);
            }
        }
        /// 
        /// Gets all the modules.
        /// 
        /// A  representing
        /// the asynchronous execution of the service.
        public async Task> GetAllModulesService()
        {
            var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllModulesService");
            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.Module)
                                    .Find(filter)
                                    .SortBy(m => m.Application)
                                    .ThenBy(m => m.Order)
                                    .ToListAsync();
                var cacheDuration = CacheHelper.GetCacheDuration(_cacheSettings);
                await cacheService.SetAsync(cacheKey, roles, cacheDuration);
                return roles;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"GetAllModulesService: Error in getting data - {ex.Message}");
                throw new Exception(ex.Message, ex);
            }
        }
        /// 
        /// Gets all the modules by modules identifier list.
        /// 
        /// The list of modules identifiers.
        /// A  representing
        /// the asynchronous execution of the service.
        public async Task> GetAllModulesByListService(string[] modules)
        {
            var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllModulesByListService", modules);
            var cachedData = await cacheService.GetAsync>(cacheKey);
            if (cachedData != null && cachedData.Any()) return cachedData;
            try
            {
                var objectIds = modules.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.Module)
                                          .Find(filter)
                                          .SortBy(m => m.Application)
                                          .ThenBy(m => m.Order)
                                          .ToListAsync();
                var cacheDuration = CacheHelper.GetCacheDuration(_cacheSettings);
                await cacheService.SetAsync(cacheKey, roles, cacheDuration);
                return roles;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"GetAllModulesByListService: Error in getting data - {ex.Message}");
                throw new Exception(ex.Message, ex);
            }
        }
        /// 
        /// Changes the status of the module.
        /// 
        /// The module identifier.
        /// The new status of the module.
        /// A  representing
        /// the asynchronous execution of the service.
        public async Task ChangeModuleStatusService(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.Module).UpdateOneAsync(filter, update);
                var updatedModule = await database.GetCollection(CollectionNames.Module)
                                    .Find(filter)
                                    .FirstOrDefaultAsync();
                return updatedModule;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"ChangeModuleStatusService: Error in getting data - {ex.Message}");
                throw new Exception(ex.Message, ex);
            }
        }
        /// 
        /// Updates a Module by id.
        /// 
        /// The Module to be updated.
        /// The Module identifier.
        /// A  representing
        /// the asynchronous execution of the service.
        public async Task UpdateModuleService(ModuleAdapter 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.Icon, entity.Icon)
                            .Set(v => v.Route, entity.Route)
                            .Set(v => v.Order, entity.Order)
                            .Set(v => v.Application, entity.Application)
                            .Set(v => v.Status, entity.Status)
                            .Set(v => v.UpdatedBy, Helper.GetEmail(httpContextAccessor))
                            .Set(v => v.UpdatedAt, DateTime.UtcNow);
                await database.GetCollection(CollectionNames.Module).UpdateOneAsync(filter, update);
                var updatedModule = await database.GetCollection(CollectionNames.Module)
                                            .Find(filter)
                                            .FirstOrDefaultAsync();
                return updatedModule;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"UpdateModuleService: Error in getting data - {ex.Message}");
                throw new Exception(ex.Message, ex);
            }
        }
        private async Task GetLastOrderModule(ModuleRequest newModule)
        {
            var filter = Builders.Filter.And(
                Builders.Filter.Eq("status", StatusEnum.Active.ToString()),
                Builders.Filter.Eq("application", newModule.Application.ToString()));
            var maxOrderModule = await database.GetCollection(CollectionNames.Module)
                                               .Find(filter)
                                               .SortByDescending(m => m.Order)
                                               .FirstOrDefaultAsync();
            return (maxOrderModule is not null && maxOrderModule.Order is not null) ? maxOrderModule.Order : 0;
        }
    }
}