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 DisplayDetailConfigRepository : MongoRepository<CardDetailsConfig>, IDisplayDetailConfigRepository
{
    private readonly ApiSettings _apiSettings;
    private readonly ILogger<DisplayDetailConfigRepository> _logger;

   

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

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

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

    public async Task<CardDetailsConfig?> GetById(ObjectId configId)
    {
        try
        {
            var result = await Collection.FindAsync(Builders<CardDetailsConfig>.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<CardDetailsConfig?> InsertOneAsyncAndReturn(CardDetailsConfig config)
    {
        try
        {
            await Collection.InsertOneAsync(config);
            return config;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex.Message);
            return null;
        }
    }

    public async Task<UpdateResponse<CardDetailsConfig?>> UpdateOne(CardDetailsConfig? config)
    {
        try
        {
            if (config == null) return new UpdateResponse<CardDetailsConfig?>(0, null);
            var filter = Builders<CardDetailsConfig>.Filter.Eq(c => c.Id, config.Id);
            var update = Builders<CardDetailsConfig>.Update
                .Set(c => c.NurseRows, config.NurseRows)
                .Set(c => c.SmartSections, config.SmartSections)
                .Set(c => c.Header, config.Header);

            // 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<CardDetailsConfig?>(result.ModifiedCount, updatedDoc);
        }
        catch (Exception e)
        {
            _logger.LogError(e.Message);
            return new UpdateResponse<CardDetailsConfig?>(0, null);
        }
    }

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

    public Task<object> UpdateCardConfigId(ObjectId? displayConfigId, ObjectId? resultId)
    {
        throw new NotImplementedException();
    }
}