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;

/// <summary>
/// Provides a MongoDB-backed repository implementation for PoCMapping entities.
/// </summary>
public class PoCMappingRepository : MongoRepository<PoCMapping>, IPoCMappingRepository
{
    private readonly ApiSettings _apiSettings;

    public PoCMappingRepository(IOptions<ApiSettings> apiSettings, IMongoDatabase database) : base(database)
    {
        _apiSettings = apiSettings.Value;
    } //For testing



    /// <summary>
    /// Retrieves the name of the mappings collection from the API settings configuration.
    /// </summary>
    /// <returns>The mappings collection name as configured in <c>_apiSettings</c>.</returns>
    public override string GetCollectionName()
    {
        return _apiSettings.Mappings;
    }

    /// <summary>
    /// Asynchronously retrieves a <see cref="PoCMapping"/> from the underlying MongoDB collection by matching its <see cref="PoCMapping.Id"/> against the supplied key, returning <c>null</c> when no matching document is found.
    /// </summary>
    /// <param name="key">The unique identifier (Id) of the <see cref="PoCMapping"/> to look up.</param>
    /// <returns>A Task TResult containing the matching PoCMapping, or <c>null</c> if no document with the specified key exists in the collection.</returns>
    public async Task<PoCMapping?> FindByKey(string key)
    {
        var filterBuilder = Builders<PoCMapping>.Filter;
        var filter = filterBuilder.Eq(config => config.Id, key);

        var result = await Collection.FindAsync(filter);

        return await result.FirstOrDefaultAsync();
    }
}