using adas_core.Application.Repositories.Interfaces;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.MongoModels;
using adas_core.Domain.Models.Responses;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using MongoDB.Driver;

namespace adas_core.Infrastructure.Repositories;

/// <summary>
/// Repository for managing ChartConfig in MongoDB. Provides methods to retrieve and manipulate ChartConfig data.
/// </summary>
public class DisplayChartConfigRepository : MongoRepository<ChartConfig>, IDisplayChartConfigRepository
{
    private readonly ApiSettings _apiSettings;
    private readonly ILogger<DisplayChartConfigRepository> _logger;


    /// <summary>
    /// Initializes a new instance of the DisplayChartConfigRepository class with the specified API settings, MongoDB database, and logger.
    /// </summary>
    /// <param name="database">The MongoDB database instance.</param>
    /// <param name="apiSettings">The API settings instance.</param>
    /// <param name="logger">The logger instance.</param>
    public DisplayChartConfigRepository(IMongoDatabase database, ApiSettings apiSettings,
        ILogger<DisplayChartConfigRepository> logger) : base(database)
    {
        _apiSettings = apiSettings;
        _logger = logger;
    }

    /// <summary>
    /// Gets the name of the MongoDB collection for ChartConfig. This method retrieves the collection name from the API settings.
    /// </summary>
    /// <returns>The name of the MongoDB collection for ChartConfig.</returns>
    public override string GetCollectionName()
    {
        return _apiSettings.DisplayChartConfig;
    }

    /// <summary>
    /// Retrieves all ChartConfig documents from the MongoDB collection. This method returns a list of ChartConfig objects representing all the configurations stored in the database.
    /// </summary>
    /// <returns>A list of ChartConfig objects representing all the configurations stored in the database.</returns>
    public async Task<List<ChartConfig>> GetAll()
    {
        var result = await Collection.Find(Builders<ChartConfig>.Filter.Empty).ToListAsync();
        return result;
    }

    /// <summary>
    /// Retrieves a ChartConfig document from the MongoDB collection by its unique identifier. This method takes an ObjectId as a parameter and returns the corresponding ChartConfig object if found, or null if no matching document is found.
    /// </summary>
    /// <param name="configId">The unique identifier of the ChartConfig document.</param>
    /// <returns>The ChartConfig object if found, or null if no matching document is found.</returns>
    public async Task<ChartConfig?> GetById(ObjectId configId)
    {
        try
        {
            var result = await Collection.FindAsync(Builders<ChartConfig>.Filter.Eq(p => p.Id, configId));
            return await result.FirstOrDefaultAsync();
        }
        catch (Exception ex)
        {
            _logger.LogError("Error on config card display repository on GetById Exception: {ex}", ex.Message);
            return null;
        }
    }

    /// <summary>
    /// Inserts a new ChartConfig document into the MongoDB collection and returns the inserted document. 
    /// This method takes a ChartConfig object as a parameter, inserts it into the database, and returns the same object if the insertion is successful. If an error occurs during the insertion process, it logs the error and returns null.
    /// </summary>
    /// <param name="config">The ChartConfig object to be inserted into the MongoDB collection.</param>
    /// <returns>The inserted ChartConfig object if successful, or null if an error occurs.</returns>
    public async Task<ChartConfig?> InsertOneAsyncAndReturn(ChartConfig config)
    {
        try
        {
            await Collection.InsertOneAsync(config);
            return config;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex.Message);
            return null;
        }
    }

    /// <summary>
    /// Updates an existing ChartConfig document in the MongoDB collection based on the provided ChartConfig object. 
    /// This method takes a ChartConfig object as a parameter, identifies the document to be updated using the Id property, and updates the BaseConfig, AxesConfig, and SeriesConfig fields of the matching document.
    /// It returns an UpdateResponse object containing the number of changes made and the updated ChartConfig document. 
    /// If an error occurs during the update process, it logs the error and returns an UpdateResponse with zero changes and null data.
    /// </summary>
    /// <param name="config">The ChartConfig object containing the updated data.</param>
    /// <returns>An UpdateResponse object containing the number of changes made and the updated ChartConfig document.</returns>
    public async Task<UpdateResponse<ChartConfig?>> UpdateOne(ChartConfig? config)
    {
        try
        {
            if (config == null) return new UpdateResponse<ChartConfig?>(0, null);
            var filter = Builders<ChartConfig>.Filter.Eq(c => c.Id, config.Id);
            var update = Builders<ChartConfig>.Update
                .Set(c => c.BaseConfig, config.BaseConfig)
                .Set(c => c.AxesConfig, config.AxesConfig)
                .Set(c => c.SeriesConfig, config.SeriesConfig);

            // Realizamos la actualización
            var result = await Collection.UpdateOneAsync(filter, update);

            // Buscamos el documento actual (ya actualizado o el existente si no hubo cambios)
            var updatedDoc = await Collection.Find(filter).FirstOrDefaultAsync();

            // result.ModifiedCount será 1 si cambió algo, o 0 si los datos eran idénticos
            return new UpdateResponse<ChartConfig?>(result.ModifiedCount, updatedDoc);
        }
        catch (Exception e)
        {
            _logger.LogError(e.Message);
            return new UpdateResponse<ChartConfig?>(0, null);
        }
    }

    /// <summary>
    /// Deletes a ChartConfig document from the MongoDB collection based on the provided unique identifier.
    /// </summary>
    /// <param name="configId">ChartConfig Id to be deleted </param>
    /// <returns></returns>
    public async Task<ChartConfig?> DeleteOne(ObjectId configId)
    {
        return await DeleteAsync(configId);
    }
}