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;

public class DisplayChartConfigRepository : MongoRepository<ChartConfig>, IDisplayChartConfigRepository
{
    private readonly ApiSettings _apiSettings;
    private readonly ILogger<DisplayDetailConfigRepository> _logger;

    

    public DisplayChartConfigRepository(IMongoDatabase database, ApiSettings apiSettings,
        ILogger<DisplayDetailConfigRepository> logger) : base(database)
    {
        _apiSettings = apiSettings;
        _logger = logger;
    }

    public override string GetCollectionName()
    {
        return _apiSettings.DisplayChartConfig;
    }

    public async Task<List<ChartConfig>> GetAll()
    {
        var result = await Collection.Find(Builders<ChartConfig>.Filter.Empty).ToListAsync();
        return result;
    }

    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;
        }
    }

    public async Task<ChartConfig?> InsertOneAsyncAndReturn(ChartConfig config)
    {
        try
        {
            await Collection.InsertOneAsync(config);
            return config;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex.Message);
            return null;
        }
    }

    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);
        }
    }

    public async Task<ChartConfig?> DeleteOne(ObjectId configId)
    {
        return await DeleteAsync(configId);
    }
}