using adas_core.Application.Repositories.Interfaces;
using adas_core.Domain.Models;
using adas_core.Domain.Models.AppSettings;
using adas_core.Domain.Models.MongoModels;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using MongoDB.Driver;
using Serilog;
using MongoUtils = adas_core.Infrastructure.Utils.MongoUtils;

namespace adas_core.Infrastructure.Repositories;

public class PatientArchiveRepository : MongoRepository<Patient>, IPatientArchiveRepository
{
    private readonly ApiSettings _apiSettings;


    public PatientArchiveRepository(IOptions<ApiSettings> apiSettings, IMongoDatabase database) : base(database)
    {
        if (apiSettings == null) throw new ArgumentNullException(nameof(apiSettings));
        _apiSettings = apiSettings.Value;
    } //For testing

   


    public override string GetCollectionName()
    {
        return _apiSettings.ArchivePatient ?? "archive_patient";
    }

    public async Task<Patient?> FindByPatientNumber(string patientNumber)
    {
        if (string.IsNullOrWhiteSpace(patientNumber)) return null;

        var filterBuilder = Builders<Patient>.Filter;
        var filter = filterBuilder.Eq(p => p.PatientNumber, patientNumber);

        var result = await Collection.FindAsync(filter);

        return await result.FirstOrDefaultAsync();
    }


    public async Task<List<Patient>> FindAll()
    {
        var filterBuilder = Builders<Patient>.Filter;
        var filter = filterBuilder.Empty;

        var result = await Collection.FindAsync(filter);

        return await result.ToListAsync();
    }

    public async Task<Patient?> SearchByPatientNumberAndDistinctUnit(string patientNumber, ObjectId unitId)
    {
        if (string.IsNullOrWhiteSpace(patientNumber)) return null;

        // Paciente ubicado en un PoC pero en diferente unidad
        var patient = await Collection.Find(Builders<Patient>.Filter.And(
            Builders<Patient>.Filter.Eq(p => p.PatientNumber, patientNumber)
        )).ToListAsync();
        // Si hay mas de una coincidencia devolvemos null por que puede no estar completo el patientNumber
        return patient.Count > 1 ? null : patient.FirstOrDefault();
    }

    public override async Task InsertOneAsync(Patient obj)
    {
        try
        {
            if (obj.PatientNumber != null)
            {
                var patient = await FindByPatientNumber(obj.PatientNumber);
                if (patient != null)
                {
                    patient.Allergies = obj.Allergies;
                    patient.Doctors = obj.Doctors;
                    patient.Procedures?.AddRange(obj.Procedures ?? []);
                    patient.Tests?.AddRange(obj.Tests ?? []);
                    patient.Treatment?.AddRange(obj.Treatment ?? []);
                    patient.Diagnosis = obj.Diagnosis;
                    patient.DiagnosisAux = obj.DiagnosisAux;
                    patient.Insulation = obj.Insulation;
                    patient.Mobility = obj.Mobility;
                    patient.Origin = obj.Origin;
                    patient.OriginAux = obj.OriginAux;
                    patient.Person = patient.Person;
                    patient.ArchiveDate = DateTime.UtcNow;
                    patient.Visits = obj.Visits;
                    patient.AccessControl = obj.AccessControl;
                    patient.AdmTime = obj.AdmTime;
                    patient.PointOfCareId = obj.PointOfCareId;
                    patient.UnitId = obj.UnitId;
                    patient.TherapeuticCeiling = obj.TherapeuticCeiling;
                    patient.Altable = obj.Altable;
                    if (patient.HistoricalLocations == null)
                        patient.HistoricalLocations = obj.HistoricalLocations;
                    else if (obj.HistoricalLocations != null)
                        foreach (var objHistoricalLocation in obj.HistoricalLocations)
                            if (!patient.HistoricalLocations.Any(c=> c.AdmTime == objHistoricalLocation.AdmTime))
                                patient.HistoricalLocations.Add(objHistoricalLocation);

                    await UpdateOneAsync(patient.Id, patient);
                }
                else
                {
                    await base.InsertOneAsync(obj);
                }
            }
            else
            {
                await base.InsertOneAsync(obj);
            }
        }
        catch (Exception e)
        {
            Log.Warning("Exception trying to insert archive patient: {obj}. Exception {e}", obj, e);
        }
    }


    public override async Task CreateIndexes()
    {
        var options = new CreateIndexOptions { Background = true, Unique = false };
        var indexes = new List<CreateIndexModel<Patient>>
        {
            new("{ patientNumber: 1 }", options)
        };
        await MongoUtils.EnsureIndexes(Collection, indexes);
    }
}