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 implementation for managing CardDetailsConfig entities in MongoDB.
/// Provides CRUD operations for display detail configurations used in nurse and smart displays.
/// </summary>
public class DisplayDetailConfigRepository : MongoRepository<CardDetailsConfig>, IDisplayDetailConfigRepository
{
    private readonly ApiSettings _apiSettings;
    private readonly ILogger<DisplayDetailConfigRepository> _logger;

    /// <summary>
    /// Initializes a new instance of the DisplayDetailConfigRepository.
    /// </summary>
    /// <param name="database">The MongoDB database instance.</param>
    /// <param name="apiSettings">API settings containing collection names configuration.</param>
    /// <param name="logger">Logger for repository operations.</param>
    public DisplayDetailConfigRepository(
        IMongoDatabase database,
        ApiSettings apiSettings,
        ILogger<DisplayDetailConfigRepository> logger
    ) : base(database)
    {
        _apiSettings = apiSettings;
        _logger = logger;
    }

    /// <summary>
    /// Gets the name of the collection for display detail configurations.
    /// </summary>
    /// <returns>The collection name from API settings.</returns>
    public override string GetCollectionName()
    {
        return _apiSettings.DisplayDetailConfig;
    }

    /// <summary>
    /// Retrieves all display detail configurations from the database.
    /// </summary>
    /// <returns>A list of all CardDetailsConfig entities.</returns>
    public async Task<List<CardDetailsConfig>> GetAll()
    {
        var result = await Collection.Find(Builders<CardDetailsConfig>.Filter.Empty).ToListAsync();
        return result;
    }

    /// <summary>
    /// Retrieves a display detail configuration by its ID.
    /// </summary>
    /// <param name="configId">The ObjectId of the detail configuration to retrieve.</param>
    /// <returns>The CardDetailsConfig if found; otherwise, null.</returns>
    /// <exception cref="Exception">Throws an exception if MongoDB query fails; returns null instead.</exception>
    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;
        }
    }

    /// <summary>
    /// Inserts a new display detail configuration and returns the inserted document.
    /// </summary>
    /// <param name="config">The CardDetailsConfig to insert.</param>
    /// <returns>The inserted CardDetailsConfig, or null if insertion fails.</returns>
    public async Task<CardDetailsConfig?> InsertOneAsyncAndReturn(CardDetailsConfig config)
    {
        try
        {
            await Collection.InsertOneAsync(config);
            return config;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex.Message);
            return null;
        }
    }

    /// <summary>
    /// Updates an existing display detail configuration with new values.
    /// </summary>
    /// <param name="config">The CardDetailsConfig with updated values.</param>
    /// <returns>An UpdateResponse containing the modified count and the updated document.</returns>
    /// <exception cref="Exception">Throws an exception if MongoDB update fails; returns UpdateResponse with null document.</exception>
    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);
        }
    }

    /// <summary>
    /// Deletes a display detail configuration by its ID.
    /// </summary>
    /// <param name="configId">The ObjectId of the configuration to delete.</param>
    /// <returns>The deleted CardDetailsConfig if found; otherwise, null.</returns>
    public async Task<CardDetailsConfig?> DeleteOne(ObjectId configId)
    {
        return await DeleteAsync(configId);
    }

    /// <summary>
    /// Updates the display configuration ID reference. This method is not implemented.
    /// </summary>
    /// <param name="displayConfigId">The ObjectId of the display configuration.</param>
    /// <param name="resultId">The new reference ID to set.</param>
    /// <returns>Always throws NotImplementedException.</returns>
    /// <exception cref="NotImplementedException">This method is not implemented.</exception>
    public Task<object> UpdateCardConfigId(ObjectId? displayConfigId, ObjectId? resultId)
    {
        throw new NotImplementedException();
    }
}