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>
/// <!-- aidoc:v1 sig=34c4715 -->
public class PoCMappingRepository : MongoRepository<PoCMapping>, IPoCMappingRepository
{
    private readonly ApiSettings _apiSettings;

    /// <summary>
    /// Initializes a new instance of the <see cref="PoCMappingRepository"/> class, storing the resolved <see cref="ApiSettings"/> and forwarding the supplied <see cref="IMongoDatabase"/> to the base repository to support persistence of PoC mappings.
    /// </summary>
    /// <param name="apiSettings">The <see cref="IOptions{ApiSettings}"/> wrapper that exposes the application's <see cref="ApiSettings"/>.</param>
    /// <param name="database">The <see cref="IMongoDatabase"/> instance passed to the base class to establish the MongoDB connection.</param>
    /// <!-- aidoc:v1 sig=443b0db body=12fddac -->
    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>
    /// <!-- aidoc:v1 sig=94e22ff body=140c15b -->
    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>
    /// <!-- aidoc:v1 sig=05f7477 body=e2c98c4 -->
    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();
    }
}