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

namespace adas_core.Infrastructure.Repositories;

public class ConfigPumpsRepository : MongoRepository<ConfigPumps>, IConfigPumpsRepository
{
    private readonly ApiSettings _apiSettings;

    public ConfigPumpsRepository(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.ConfigPumps ?? "config_pumps";
    }

    public async Task<List<ConfigPumps>?> GetAllConfigs()
    {
        var result = await Collection.FindAsync(Builders<ConfigPumps>.Filter.Empty);

        return result.ToList();
    }

    public async Task<ConfigPumps?> FindById(string id)
    {
        var result = await Collection.FindAsync(Builders<ConfigPumps>.Filter.Eq(x => x.Id, id));

        return await result.FirstOrDefaultAsync();
    }

    public async Task<ConfigPumps?> UpdateConfig(ConfigPumps config)
    {
        var filter = Builders<ConfigPumps>.Filter.Eq("_id", config.Id);
        var update = Builders<ConfigPumps>.Update.Set(c => c.Items, config.Items);

        return await Collection.FindOneAndUpdateAsync(filter, update,
            new FindOneAndUpdateOptions<ConfigPumps, ConfigPumps> { ReturnDocument = ReturnDocument.After });
    }

    public async Task<bool> DeleteConfig(ConfigPumps config)
    {
        var filter = Builders<ConfigPumps>.Filter.Eq("_id", config.Id);
        await Collection.DeleteOneAsync(filter);

        var result = await FindById(config.Id);
        return result == null;
    }
}