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 AppointmentArchiveRepository : MongoRepository<PatientAppointment>, IAppointmentArchiveRepository
{
    private readonly ApiSettings _apiSettings;


    public AppointmentArchiveRepository(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(PatientAppointment appointment)
    {
        await Collection.InsertOneAsync(appointment);
    }


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

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

        var bulkInsert = await Collection.BulkWriteAsync(writes);

        return bulkInsert.InsertedCount;
    }

    public override string GetCollectionName()
    {
        return _apiSettings.ArchivePatientsAppointments ?? "archive_patients_appointments";
    }

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

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

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