using adas_core.Application.Exceptions;
using adas_core.Application.Repositories.Interfaces;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Enums;
using adas_core.Domain.Models;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.MongoModels;
using adas_core.Domain.Models.Pumps;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace adas_core.Application.Services;

public class ConfigPumpsService(
    IConfigPumpsRepository configPumpsRepository,
    IOptions<ApiSettings> apiSettings,
    ILogger<ConfigPumpsService> logger,
    IHttpContextAccessor httpContextAccessor,
    ILocalAuditService auditService)
    : IConfigPumpsService
{
    private static ConfigPumps? _config;
    private static DateTime _nextRefresh = DateTime.MinValue;

    private readonly bool _configPumpsRequired = apiSettings.Value.ConfigPumpsRequired;
    private readonly string _key = apiSettings.Value.ConfigPumpsKey ?? "PV1";
    private readonly int? _refreshTimeout = apiSettings.Value.ConfigObservation?.Refresh;

    /// <summary>
    /// Maps a <see cref="PumpObservation"/> using its alarm type configuration. Returns the original observation unchanged when configuration-based pump mapping is not required or when no matching configuration is found.
    /// </summary>
    /// <param name="obs">The pump observation to map, containing the alarm type used for configuration lookup.</param>
    /// <returns>The mapped pump observation, or the original observation when mapping is skipped or the configuration lookup yields no result.</returns>
    public async Task<PumpObservation> Map(PumpObservation obs)
    {
        if (!_configPumpsRequired) return obs;

        var conf = !string.IsNullOrEmpty(obs.AlarmType.ToString())
            ? await Get(obs.AlarmType.ToString() ?? string.Empty)
            : null;

        if (conf == null) return obs;

        return await MapConf(obs, conf);
    }

    /// <summary>
    /// Retrieves all available pump configurations from the underlying repository.
    /// </summary>
    /// <returns>A task that represents the asynchronous operation, containing a list of <see cref="ConfigPumps"/> if any are available, or <c>null</c> when no configurations exist.</returns>
    public async Task<List<ConfigPumps>?> GetAllPumpConfigs()
    {
        return await configPumpsRepository.GetAllConfigs();
    }

    /// <summary>
    /// Retrieves the configuration for a pump identified by its unique identifier from the configuration repository.
    /// Returns <c>null</c> when no matching pump configuration is found.
    /// </summary>
    /// <param name="id">The unique identifier of the pump configuration to retrieve.</param>
    /// <returns>A <see cref="ConfigPumps"/> instance if a matching configuration is found; otherwise, <c>null</c>.</returns>
    public async Task<ConfigPumps?> GetPumpConfigById(string id)
    {
        return await configPumpsRepository.FindById(id);
    }

    /// <summary>
    /// Retrieves the list of configuration items associated with the config pump identified by the given identifier. Returns <c>null</c> when no matching config pump is found in the repository.
    /// </summary>
    /// <param name="id">The unique identifier of the config pump to look up.</param>
    /// <returns>A task that resolves to the list of <see cref="ConfigPumpItem"/> entries, or <c>null</c> if the config pump does not exist.</returns>
    public async Task<List<ConfigPumpItem>?> GetConfigItems(string id)
    {
        var result = await configPumpsRepository.FindById(id);
        return result?.Items;
    }

    /// <summary>
    /// Updates the pump configuration in the repository and records an audit log of the change.
    /// Throws a <see cref="ConflictException"/> if the update operation returns null.
    /// </summary>
    /// <param name="pumpConfig">The pump configuration to update, identified by its <see cref="ConfigPumps.Id"/>.</param>
    /// <returns>A task representing the asynchronous operation, containing the updated <see cref="ConfigPumps"/>.</returns>
    /// <exception cref="ConflictException">Thrown when the update operation fails.</exception>
    public async Task<ConfigPumps?> UpdatePumpConfig(ConfigPumps pumpConfig)
    {
        var oldPumpConfig = configPumpsRepository.FindById(pumpConfig.Id);
        var newPumpConfig = await configPumpsRepository.UpdateConfig(pumpConfig) ??
                            throw new ConflictException(HttpEnum.ErrorMessage.ConflictUpdateFailed);
        await auditService.CreateAuditLogAsync(httpContextAccessor.HttpContext?.User!, oldPumpConfig, newPumpConfig);
        return newPumpConfig;
    }

    /// <summary>
    /// Inserts a new pump configuration into the repository, records an audit log entry for the operation, and returns the inserted configuration. If the configuration cannot be retrieved after insertion or any exception occurs, the error is logged and the method returns <c>null</c>.
    /// </summary>
    /// <param name="pumpConfig">The pump configuration to insert.</param>
    /// <returns>The inserted <see cref="ConfigPumps"/> on success; otherwise, <c>null</c> when an error occurs during the operation.</returns>
    /// <exception cref="ConflictException">Thrown when the inserted configuration cannot be found in the repository after insertion.</exception>
    public async Task<ConfigPumps?> InsertPumpConfig(ConfigPumps pumpConfig)
    {
        try
        {
            await configPumpsRepository.InsertOneAsync(pumpConfig);
            var newPumpConfig = await configPumpsRepository.FindById(pumpConfig.Id) ??
                                throw new ConflictException(HttpEnum.ErrorMessage.ConflictCreationFailed);
            await auditService.CreateAuditLogAsync(httpContextAccessor.HttpContext?.User!, null, newPumpConfig);
            return newPumpConfig;
        }
        catch (Exception ex)
        {
            logger.LogError("ERROR inserting config_pumps: {key}. Exception: {exMessage} ", pumpConfig.Id, ex.Message);
            return null;
        }
    }

    /// <summary>
    /// Deletes a pump configuration asynchronously, auditing the change on success and returning <c>false</c> if the repository operation reports an error or an exception is thrown.
    /// </summary>
    /// <param name="config">The <see cref="ConfigPumps"/> instance representing the pump configuration to delete.</param>
    /// <returns>A task that resolves to <c>true</c> when the configuration is deleted and the audit log is recorded; <c>false</c> when the delete operation fails or an exception occurs.</returns>
    public async Task<bool> DeletePumpConfig(ConfigPumps config)
    {
        try
        {
            var result = await configPumpsRepository.DeleteConfig(config);

            if (result)
            {
                logger.LogError("ERROR deleting config_pumps: {key}.  ", config.Id);
                return false;
            }

            await auditService.CreateAuditLogAsync(httpContextAccessor.HttpContext?.User!, config, null);
            return true;
        }
        catch (Exception ex)
        {
            logger.LogError("ERROR deleting config_pumps: {key}. Exception: {exMessage} ", config.Id, ex.Message);
            return false;
        }
    }

    /// <summary>
    /// Determines the retention actions to apply for a pump observation based on its configuration.
    /// When a retention policy is configured, returns the configured policy and its value; otherwise, falls back to <see cref="RetentionPolicy.NoDelete"/> with a null value.
    /// </summary>
    /// <param name="obs">The pump observation for which to evaluate the retention policy.</param>
    /// <returns>A task containing the retention result with the applicable policy and associated value, or a default NoDelete result when no policy is configured.</returns>
    public async Task<ObservatitonRetentionResult?> RetentionActions(PumpObservation obs)
    {
        //TODO sacarlo de la configuración específica de Bombas
        var conf = await Get(obs);
        return conf is { RetentionPolicy: not null } ?
            new ObservatitonRetentionResult(conf.RetentionPolicy.Value, conf.RetentionPolicyValue) :
            new ObservatitonRetentionResult(RetentionPolicy.NoDelete, null);
    }

    /// <summary>
    /// Maps the UI configuration from a <see cref="ConfigPumpItem"/> onto a <see cref="PumpObservation"/>, assigning the configuration only when it is provided and non-empty.
    /// </summary>
    /// <param name="obs">The pump observation that will receive the UI configuration.</param>
    /// <param name="conf">The configuration source whose UI configuration is applied to <paramref name="obs"/> when present.</param>
    /// <returns>A completed <see cref="Task{PumpObservation}"/> containing the updated observation.</returns>
    private static Task<PumpObservation> MapConf(PumpObservation obs, ConfigPumpItem conf)
    {
        if (conf.UiConfiguration != null && conf.UiConfiguration.Count != 0)
            obs.UiConfiguration = conf.UiConfiguration;

        return Task.FromResult(obs);
    }

    /// <summary>
    /// Retrieves a <see cref="ConfigPumpItem"/> matching the specified alarm type by parsing the input string into a <see cref="PumpEnum.AlarmType"/> and searching the configuration items.
    /// </summary>
    /// <param name="alarmType">The string representation of the alarm type to look up; if it cannot be parsed into a valid <see cref="PumpEnum.AlarmType"/>, the method returns <c>null</c>.</param>
    /// <returns>A <see cref="ConfigPumpItem"/> whose <c>AlarmType</c> matches the parsed value, or <c>null</c> if parsing fails or no matching item is found.</returns>
    private async Task<ConfigPumpItem?> Get(string alarmType)
    {
        if (!Enum.TryParse(alarmType, out PumpEnum.AlarmType alarmTypeParsed))
            return null;
        var result = await GetConfig();
        return result?.Items?.FirstOrDefault(i => i.AlarmType == alarmTypeParsed);
    }

    /// <summary>
    /// Retrieves the configuration item associated with the specified pump observation by matching its message type against the loaded configuration entries.
    /// Returns null when the configuration, its items collection, or a matching entry is not found.
    /// </summary>
    /// <param name="pobs">The pump observation whose <c>MessageType</c> is used to locate the corresponding configuration entry.</param>
    /// <returns>A <see cref="ConfigPumpItem"/> matching the observation's message type, or <c>null</c> if the configuration is unavailable or no matching item exists.</returns>
    private async Task<ConfigPumpItem?> Get(PumpObservation pobs)
    {
        var config = await GetConfig();
        return config?.Items?.FirstOrDefault(i => i.Type == pobs.MessageType);
    }
    /// <summary>
    /// Asynchronously retrieves the list of configuration pump items by fetching the current configuration.
    /// Returns a null list if the underlying configuration is not available.
    /// </summary>
    /// <returns>A task containing a list of <see cref="ConfigPumpItem"/> objects, or <c>null</c> if the configuration could not be retrieved.</returns>
    public async Task<List<ConfigPumpItem>?> Get()
    {
        var result = await GetConfig();
        return result?.Items;
    }


    /// <summary>
    /// Retrieves the configuration associated with the current key, returning a cached value when it has not yet expired.
    /// Falls back to fetching from the repository when the cache is missing or stale, and returns <c>null</c> if an error occurs during retrieval.
    /// </summary>
    /// <returns>A task containing the <see cref="ConfigPumps"/> instance if available; otherwise, <c>null</c> when the repository lookup fails.</returns>
    private async Task<ConfigPumps?> GetConfig()
    {
        try
        {
            if (_config != null && DateTime.Now <= _nextRefresh)
                return _config;
            _config = await configPumpsRepository.FindById(_key);
            _nextRefresh = _refreshTimeout.HasValue
                ? DateTime.Now.AddSeconds(_refreshTimeout.Value)
                : DateTime.MinValue;

            return _config;
        }
        catch (Exception ex)
        {
            logger.LogError("ERROR READ config_pumps: {key}. Exception: {exMessage} ", _key, ex.Message);
            return null;
        }
    }
}