using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
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>
    /// Repositorio de archivo para observaciones de bombas.
    /// Colección: archive_pumpobservations (configurable por ApiSettings.ArchivePumpObservations).
    /// </summary>
    /// <!-- aidoc:v1 sig=46323e9 -->
    public class PumpArchiveRepository : MongoRepository<PumpObservation>, IPumpArchiveRepository
    {
        private readonly ApiSettings _apiSettings;

        /// <summary>
        /// Initializes a new instance of the <see cref="PumpArchiveRepository"/> class, forwarding <paramref name="database"/> to the base repository and storing the resolved <see cref="ApiSettings"/> configuration for subsequent operations.
        /// </summary>
        /// <param name="apiSettings">The <see cref="IOptions{ApiSettings}"/> wrapper whose <see cref="IOptions{T}.Value"/> supplies the current <see cref="ApiSettings"/>.</param>
        /// <param name="database">The <see cref="IMongoDatabase"/> connection passed to the base class constructor.</param>
        /// <!-- aidoc:v1 sig=875c7ca body=12fddac -->
        public PumpArchiveRepository(IOptions<ApiSettings> apiSettings, IMongoDatabase database)
            : base(database)
        {
            _apiSettings = apiSettings.Value;
        }


        /// <summary>
        /// Returns the agreed MongoDB collection name used to store archived pump observations for patients, falling back to the default value when the corresponding setting is not configured.
        /// </summary>
        /// <returns>The collection name to use, either the value configured in <c>ArchivePatientsPumpobservations</c> or the default <c>archive_pumpobservations</c>.</returns>
        /// <!-- aidoc:v1 sig=94e22ff body=09ed313 -->
        public override string GetCollectionName()
        {
            // Nombre de colección pactado: "archive_pumpobservations"
            return _apiSettings.ArchivePatientsPumpobservations ?? "archive_pumpobservations";
        }

        /// <summary>
        /// Creates the MongoDB indexes required by the <see cref="PumpObservation"/> collection: an ascending index on <see cref="PumpObservation.PatientId"/> for patient-based lookups and audits, a compound index on <see cref="PumpObservation.DeviceId"/> (ascending) and <see cref="PumpObservation.Time"/> (descending) for per-device timelines, and a descending index on <see cref="PumpObservation.Time"/> for chronological ordering.
        /// </summary>
        /// <!-- aidoc:v1 sig=4955da2 body=2c1d18d -->
        public override async Task CreateIndexes()
        {
            var indexModels = new List<CreateIndexModel<PumpObservation>>
            {
                // Búsquedas por paciente (audit / restauraciones)
                new CreateIndexModel<PumpObservation>(
                    Builders<PumpObservation>.IndexKeys.Ascending(x => x.PatientId),
                    new CreateIndexOptions { Name = "ix_patientId" }),

                // Timeline por dispositivo (útil para auditorías por equipo)
                new CreateIndexModel<PumpObservation>(
                    Builders<PumpObservation>.IndexKeys
                        .Ascending(x => x.DeviceId)
                        .Descending(x => x.Time),
                    new CreateIndexOptions { Name = "ix_deviceId_time" }),

                // Orden temporal simple
                new CreateIndexModel<PumpObservation>(
                    Builders<PumpObservation>.IndexKeys.Descending(x => x.Time),
                    new CreateIndexOptions { Name = "ix_time" })
            };

            await Collection.Indexes.CreateManyAsync(indexModels);
        }

        /// <summary>
        /// Asynchronously inserts a <see cref="PumpObservation"/> into the underlying MongoDB collection.
        /// </summary>
        /// <param name="obs">The pump observation to persist.</param>
        /// <!-- aidoc:v1 sig=2e9b63d body=ff40c9a -->
        public async Task InsertAsync(PumpObservation obs)
                {
                    await Collection.InsertOneAsync(obs);
                }

        /// <summary>
        /// Asynchronously inserts a batch of pump observations into the underlying data store. If the collection is empty, the method completes without performing any insertion.
        /// </summary>
        /// <param name="observations">The pump observations to insert into the collection.</param>
        /// <!-- aidoc:v1 sig=1891edb body=80cfb77 -->
        public async Task InsertManyAsync(IEnumerable<PumpObservation> observations)
                {
                    var list = observations as IList<PumpObservation> ?? observations.ToList();
                    if (list.Count == 0) return;
        
                    await Collection.InsertManyAsync(list);
                }

        /// <summary>
        /// Retrieves a collection of <see cref="PumpObservation"/> records for a specific patient, optionally filtered by a time range and limited in count, sorted by time in descending order.
        /// </summary>
        /// <param name="patientId">The identifier of the patient whose pump observations are being queried.</param>
        /// <param name="from">Optional inclusive lower bound for the observation time. When provided, only observations on or after this time are returned.</param>
        /// <param name="to">Optional inclusive upper bound for the observation time. When provided, only observations on or before this time are returned.</param>
        /// <param name="limit">Optional maximum number of observations to return. When null, all matching observations are returned.</param>
        /// <returns>A task that represents the asynchronous operation. The task result contains an <see cref="IEnumerable{PumpObservation}"/> of matching observations ordered from newest to oldest.</returns>
        /// <!-- aidoc:v1 sig=d24c731 body=afb5adf -->
        public async Task<IEnumerable<PumpObservation>> FindByPatientIdAsync(
                    ObjectId patientId, DateTime? from = null, DateTime? to = null, int? limit = null)
                {
                    var filter = Builders<PumpObservation>.Filter.Eq(x => x.PatientId, patientId);
        
                    if (from.HasValue)
                        filter &= Builders<PumpObservation>.Filter.Gte(x => x.Time, from.Value);
        
                    if (to.HasValue)
                        filter &= Builders<PumpObservation>.Filter.Lte(x => x.Time, to.Value);
        
                    var query = Collection.Find(filter).SortByDescending(x => x.Time);
        
                    if (limit.HasValue)
                        query = query.Limit(limit.Value) as IOrderedFindFluent<PumpObservation, PumpObservation>;
        
                    return await query.ToListAsync();
                }

        /// <summary>
        /// Deletes all pump observations whose recording time is earlier than the specified cutoff date.
        /// </summary>
        /// <param name="addDays">The cutoff date; observations with a timestamp before this value are removed.</param>
        /// <!-- aidoc:v1 sig=f776d6a body=426aa60 -->
        public async Task DeleteBeforeDate(DateTime addDays)
                {
                    var filter = Builders<PumpObservation>.Filter.Lt(x => x.Time, addDays);
                    await Collection.DeleteManyAsync(filter);
                }
    }
}