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

namespace adas_core.Infrastructure.Repositories;

public class TreatmentArchiveRepository : MongoRepository<PatientTreatment>, ITreatmentArchiveRepository
{
    private readonly ApiSettings _apiSettings;

    public TreatmentArchiveRepository(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(PatientTreatment patientTreatment)
    {
        await Collection.InsertOneAsync(patientTreatment);
    }

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

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

        var bulkInsert = await Collection.BulkWriteAsync(writes);

        return bulkInsert.InsertedCount;
    }

    public async Task<List<PatientTreatment>> FindAllFromPatient(ObjectId patientId)
    {
        var filter = Builders<PatientTreatment>.Filter.Eq(t => t.PatientId, patientId);
        var result = await Collection.FindAsync(filter);

        return await result.ToListAsync();
    }

    public override string GetCollectionName()
    {
        return _apiSettings.ArchivePatientsTreatments ?? "archive_patients_treatments";
    }
}