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

namespace adas_core.Infrastructure.Repositories;

public class DiagnosisArchiveRepository : MongoRepository<PatientDiagnosis>, IDiagnosisArchiveRepository
{
    private readonly ApiSettings _apiSettings;

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

    public override async Task InsertOneAsync(PatientDiagnosis patientDiagnosis)
    {
        await Collection.InsertOneAsync(patientDiagnosis);
    }

    public async Task DeleteBeforeDate(DateTime date)
    {
        var filter = Builders<PatientDiagnosis>.Filter.Lt(po => po.Time, date);
        await Collection.DeleteManyAsync(filter);
    }

    public async Task<long> InsertBatch(IEnumerable<PatientDiagnosis> observations)
    {
        var writes = new List<WriteModel<PatientDiagnosis>>();
        writes.AddRange(observations.Select(d => new InsertOneModel<PatientDiagnosis>(d)));

        var bulkInsert = await Collection.BulkWriteAsync(writes);

        return bulkInsert.InsertedCount;
    }

    public override string GetCollectionName()
    {
        return _apiSettings.ArchivePatientsDiagnosis ?? "archive_patients_diagnosis";
    }

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

        var indexes = new List<CreateIndexModel<PatientDiagnosis>>
        {
            new("{ patientid: 1 }", options)
        };

        await MongoUtils.EnsureIndexes(Collection, indexes);
    }
}