using adas_core.Application.Exceptions;
using adas_core.Application.Repositories.Interfaces;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.Filter;
using adas_core.Domain.Models.MongoModels;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using MongoDB.Driver;
using Serilog;
using System.Text.RegularExpressions;
using MongoUtils = adas_core.Infrastructure.Utils.MongoUtils;

namespace adas_core.Infrastructure.Repositories;

public class DisplayRepository : MongoRepository<Display>, IDisplayRepository
{
    #region Properties

    private readonly ApiSettings _apiSettings;

    private readonly ILogger<DisplayRepository> _logger;
    // private readonly Idisplay<DisplayRepository> _logger;

    #endregion

    #region Constructor

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

   

    #endregion

    #region Methods

    #region Create

    public override async Task CreateIndexes()
    {
        var options = new CreateIndexOptions<Display> { Background = true, Unique = false };

        var indexes = new List<CreateIndexModel<Display>>
        {
            new("{ displayConfigId: 1 }", options),
            new("{ unitId: 1 }", options)
        };

        await MongoUtils.EnsureIndexes(Collection, indexes);
    }

    #endregion

    #region Read

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

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

    public IFindFluent<Display, Display> GetPaginatedDisplays(PaginationFilter filter)
    {
        var filterBuilder = Builders<Display>.Filter;
        var sort = Builders<Display>.Sort.Ascending("name");
        var filters = new List<FilterDefinition<Display>>();

        if (filter.FilteredRequest == null)
            return CreateFindFluent(filters, sort);

        // Text filter seguro
        if (!string.IsNullOrWhiteSpace(filter.FilteredRequest.Text))
        {
            var textFilter = filter.FilteredRequest.Text;

            if (textFilter.Length > 100)
                throw new BadRequestException("Text filter too long");

            var escapedTextFilter = Regex.Escape(textFilter);

            filters.Add(filterBuilder.Regex(
                d => d.Name,
                new BsonRegularExpression(escapedTextFilter, "i")
            ));
        }

        // UnitId
        if (!string.IsNullOrWhiteSpace(filter.FilteredRequest.UnitId) &&
            ObjectId.TryParse(filter.FilteredRequest.UnitId, out var unitId))
        {
            filters.Add(filterBuilder.Eq(d => d.UnitId, unitId));
        }
        // UnitName fallback
        else if (!string.IsNullOrWhiteSpace(filter.FilteredRequest.UnitName))
        {
            filters.Add(filterBuilder.Eq(d => d.Unit!.Name, filter.FilteredRequest.UnitName));
        }

        // DisplayType
        if (filter.FilteredRequest.DisplayType != null)
        {
            filters.Add(filterBuilder.Eq(d => d.Type, filter.FilteredRequest.DisplayType));
        }

        return CreateFindFluent(filters, sort);
    }

    private IFindFluent<Display, Display> CreateFindFluent(List<FilterDefinition<Display>> filters,
        SortDefinition<Display> sort)
    {
        var combinedFilter = filters.Any()
            ? Builders<Display>.Filter.And(filters)
            : Builders<Display>.Filter.Empty; // Filtra todo si no hay filtros
        return Collection.Find(combinedFilter).Sort(sort);
    }

    public async Task<List<Display>> GetByPointOfCare(PointOfCare pointOfCare)
    {
        var filter = Builders<Display>.Filter.AnyEq(x => x.PointOfCareIdList, pointOfCare.Id);
        var result = await Collection.Find(filter).ToListAsync();
        return result;
    }

    public async Task<Display?> GetByName(string name)
    {
        var result = await Collection.FindAsync(Builders<Display>.Filter.Eq(p => p.Name, name));
        return await result.FirstOrDefaultAsync();
    }

    public async Task<Display?> GetById(ObjectId id)
    {
        var result = await Collection.FindAsync(Builders<Display>.Filter.Eq(p => p.Id, id));

        return await result.FirstOrDefaultAsync();
    }

    public async Task<Display?> GetByIdWithConfigDisplay(ObjectId id)
    {
        var pipeline = new BsonDocument[]
        {
            new("$match", new BsonDocument("_id", id)),
            new("$lookup", new BsonDocument
            {
                { "from", "config_displays" },
                { "localField", "displayConfigId" }, // Asumiendo que este es el campo que refiere a config_display
                { "foreignField", "_id" },
                { "as", "DisplayNurse" }
            }),
            new("$unwind", new BsonDocument
            {
                { "path", "$configDisplay" },
                { "preserveNullAndEmptyArrays", true }
            })
        };

        var result = await Collection.AggregateAsync<Display>(pipeline, new AggregateOptions { AllowDiskUse = true });
        return await result.FirstOrDefaultAsync();
    }

    public async Task<List<Display>> GetByUnitId(ObjectId id)
    {
        var filter = Builders<Display>.Filter.Eq(p => p.UnitId, id);
        var result = await Collection.Find(filter).ToListAsync();
        return result;
    }

    public async Task<long> CountByUnitId(ObjectId unitId)
    {
        try
        {
            return await Collection.CountDocumentsAsync(Builders<Display>.Filter.Eq(p => p.UnitId, unitId));
        }
        catch (Exception e)
        {
            _logger.LogError(e.Message);
            return 0;
        }
    }

    public async Task<List<Display>> GetByConfigId(ObjectId id)
    {
        var result = await Collection.FindAsync(Builders<Display>.Filter.Eq(p => p.DisplayConfigId, id));
        return result.ToList();
    }

    public async Task<List<Display>> GetByCardConfigId(ObjectId configId)
    {
        try
        {
            var aggregate = Collection.Aggregate()
                // 1. Unimos la colección Display con DisplayConfig
                .Lookup(
                    _apiSettings.DisplaysConfig, // Nombre de la colección externa
                    "displayConfigId", // Campo local en la colección 'Display'
                    "_id", // Campo en la colección 'DisplayConfig'
                    "displayConfig" // Nombre de la propiedad en la clase C# (debe coincidir)
                )
                // 2. Convertimos el array resultante del lookup en un objeto único
                .Unwind("displayConfig", new AggregateUnwindOptions<BsonDocument>
                {
                    PreserveNullAndEmptyArrays = false // Si no tiene config, no nos interesa
                })
                // 3. Filtramos por la propiedad interna del objeto ya "unido"
                // Nota: Usamos el nombre del campo tal cual está en el BSON (normalmente camelCase)
                .Match(Builders<BsonDocument>.Filter.Eq("displayConfig.cardConfigId", configId))

                // 4. Casteamos el resultado de vuelta a nuestra clase Display
                .As<Display>();

            return await aggregate.ToListAsync();
        }
        catch (Exception ex)
        {
            _logger.LogError("Error en GetByCardConfigId: {ex}", ex.Message);
            return [];
        }
    }

    public async Task<long> IsDisplayConfigInUse(ObjectId displayConfigId)
    {
        return await Collection.CountDocumentsAsync(
            Builders<Display>.Filter.Eq(p => p.DisplayConfigId, displayConfigId));
    }

    #endregion

    #region Update

    public async Task<Display?> UpdatePointOfCareList(ObjectId objectId, List<ObjectId> listPocObId)
    {
        try
        {
            var filter = Builders<Display>.Filter.Eq("Id", objectId);
            var update = Builders<Display>.Update
                .Set(c => c.PointOfCareIdList, listPocObId);

            return await Collection.FindOneAndUpdateAsync(filter, update,
                new FindOneAndUpdateOptions<Display, Display> { ReturnDocument = ReturnDocument.After });
        }
        catch (Exception e)
        {
            _logger.LogError($"Unable to update pointOfCareList from Display Exception {e}");
            return null;
        }
    }

    public async Task<Display?> UpdateConfig(ObjectId objectId, DisplayConfig config)
    {
        try
        {
            var filter = Builders<Display>.Filter.Eq("Id", objectId);
            var update = Builders<Display>.Update
                .Set(c => c.DisplayConfig, config);

            return await Collection.FindOneAndUpdateAsync(filter, update,
                new FindOneAndUpdateOptions<Display, Display> { ReturnDocument = ReturnDocument.After });
        }
        catch (Exception e)
        {
            _logger.LogError($"Unable to update config from Display Exception {e.Message}");
            return null;
        }
    }

    public async Task<Display?> UpdateConfigId(ObjectId objectId, ObjectId displayConfigId)
    {
        try
        {
            var filter = Builders<Display>.Filter.Eq("Id", objectId);
            var update = Builders<Display>.Update
                .Set(c => c.DisplayConfigId, displayConfigId);

            return await Collection.FindOneAndUpdateAsync(filter, update,
                new FindOneAndUpdateOptions<Display, Display> { ReturnDocument = ReturnDocument.After });
        }
        catch (Exception e)
        {
            _logger.LogError($"Unable to update config from Display Exception {e.Message}");
            return null;
        }
    }

    public async Task<Display?> UpdateConfigPreset(ObjectId objectIdDisplay, ObjectId objectIdConfigDisplay)
    {
        try
        {
            var filter = Builders<Display>.Filter.Eq("Id", objectIdDisplay);
            var update = Builders<Display>.Update
                .Set(c => c.DisplayConfigId, objectIdConfigDisplay);

            return await Collection.FindOneAndUpdateAsync(filter, update,
                new FindOneAndUpdateOptions<Display, Display> { ReturnDocument = ReturnDocument.After });
        }
        catch (Exception e)
        {
            _logger.LogError($"Unable to update config from Display Exception: {e.Message}");
            return null;
        }
    }

    public async Task<Display> UpdateName(Display display, string name)
    {
        try
        {
            var filter = Builders<Display>.Filter.Eq("_id", display.Id);

            var update = Builders<Display>.Update
                .Set(d => d.Name, name);

            return await Collection.FindOneAndUpdateAsync(filter, update,
                new FindOneAndUpdateOptions<Display, Display> { ReturnDocument = ReturnDocument.After });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex.Message);
            throw;
        }
    }

    #endregion

    #region Delete

    public async Task<bool> DeleteManyByUnitId(ObjectId unitId)
    {
        try
        {
            var filter = Builders<Display>.Filter.Where(p => p.UnitId == unitId);
            await Collection.DeleteManyAsync(filter);

            return true;
        }
        catch (Exception e)
        {
            Log.Logger.Error(e.Message);
            return false;
        }
    }

    #endregion

    #endregion
}