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

namespace adas_core.Infrastructure.Repositories;

/// <summary>
/// Represents a MongoDB-backed repository for <see cref="PumpAlarmEvent"/> documents, exposing pump alarm event-specific data access through the <see cref="IPumpAlarmEventRepository"/> contract.
/// </summary>
/// <remarks>
/// Inherits the generic MongoDB persistence capabilities of <see cref="MongoRepository{TDocument}"/>, specializing them for the <see cref="PumpAlarmEvent"/> entity type.
/// </remarks>
public class PumpAlarmEventRepository : MongoRepository<PumpAlarmEvent>, IPumpAlarmEventRepository
{
    private readonly ApiSettings _apiSettings;

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

 

    public override string GetCollectionName()
    {
        return _apiSettings.PumpAlarmEvent ?? "pump_alarm_event";
    }

    public override async Task CreateIndexes()
    {
        var indexModels = new List<CreateIndexModel<PumpAlarmEvent>>
        {
            // Principal para consultas por bomba y orden temporal
            new(
                Builders<PumpAlarmEvent>.IndexKeys
                    .Ascending(x => x.DeviceId)
                    .Descending(x => x.Time),
                new CreateIndexOptions { Name = "ix_deviceId_time" }),

            // Índice temporal
            new(
                Builders<PumpAlarmEvent>.IndexKeys.Descending(x => x.Time),
                new CreateIndexOptions { Name = "ix_time" }),

            // por paciente
            new(
                Builders<PumpAlarmEvent>.IndexKeys.Ascending(x => x.PatientId),
                new CreateIndexOptions { Name = "ix_patientId" }),

            //por tipo de alarma dentro de una bomba
            new(
                Builders<PumpAlarmEvent>.IndexKeys
                    .Ascending(x => x.DeviceId)
                    .Ascending(x => x.AlarmType),
                new CreateIndexOptions { Name = "ix_device_alarmType" })
        };

        await Collection.Indexes.CreateManyAsync(indexModels);
    }


    public async Task InsertAsync(PumpAlarmEvent alarmEvent)
    {
        await Collection.InsertOneAsync(alarmEvent);
    }

    public async Task<IEnumerable<PumpAlarmEvent>> FindByDeviceIdAsync(string deviceId, DateTime? from = null,
        DateTime? to = null, int? limit = null)
    {
        var filter = Builders<PumpAlarmEvent>.Filter.Eq(x => x.DeviceId, deviceId);

        if (from.HasValue)
            filter &= Builders<PumpAlarmEvent>.Filter.Gte(x => x.Time, from.Value);

        if (to.HasValue)
            filter &= Builders<PumpAlarmEvent>.Filter.Lte(x => x.Time, to.Value);

        var find = Collection.Find(filter).SortByDescending(x => x.Time);
        if (limit.HasValue) find = find.Limit(limit.Value) as IOrderedFindFluent<PumpAlarmEvent, PumpAlarmEvent>;

        return await find.ToListAsync();
    }

    public async Task<PumpAlarmEvent?> FindLastByDeviceIdAsync(string deviceId)
    {
        return await Collection
            .Find(x => x.DeviceId == deviceId)
            .SortByDescending(x => x.Time)
            .FirstOrDefaultAsync();
    }

    public async Task DeleteByPatientId(ObjectId patientId)
    {
        await Collection.DeleteManyAsync(x => x.PatientId == patientId);
    }
        
        
    public async Task<long> UpdateManyObjectIdByFiledNameAsync(string fieldName, ObjectId newId, ObjectId oldId)
    {
        var filter = Builders<PumpAlarmEvent>.Filter.Eq(fieldName, oldId);
        var update = Builders<PumpAlarmEvent>.Update.Set(fieldName, newId);
        var result = await Collection.UpdateManyAsync(filter, update);
        return result.ModifiedCount;
    }

}