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

namespace adas_core.Infrastructure.Repositories;

/// <summary>
/// Represents a MongoDB repository for <see cref="ServiceConfig"/> entities, implementing the <see cref="IServiceConfigRepository"/> contract to provide data access operations.
/// </summary>
public class ServiceConfigRepository : MongoRepository<ServiceConfig>, IServiceConfigRepository
{
    private readonly ApiSettings _apiSettings;

    public ServiceConfigRepository(IOptions<ApiSettings> apiSettings, IMongoDatabase database) : base(database)
    {
        if (apiSettings == null) throw new ArgumentNullException(nameof(apiSettings));
        _apiSettings = apiSettings.Value;
    } //For testing

    

    /// <summary>
    /// Retrieves the service configuration collection name from API settings, falling back to the default "service_config" when no value is configured.
    /// </summary>
    /// <returns>The configured service collection name, or the default "service_config" when the API setting is null.</returns>
    public override string GetCollectionName()
        {
            return _apiSettings.ServiceConfig ?? "service_config";
        }

    /// <summary>
    /// Finds a <see cref="ServiceConfig"/> document by matching its string identifier (<c>StrId</c>) with the provided value.
    /// Returns <c>null</c> when no matching configuration exists in the collection.
    /// </summary>
    /// <param name="id">The string identifier used to look up the service configuration.</param>
    /// <returns>A task that represents the asynchronous operation, containing the matching <see cref="ServiceConfig"/> or <c>null</c> if not found.</returns>
    public async Task<ServiceConfig?> FindById(string id)
        {
            var result = await Collection.FindAsync(Builders<ServiceConfig>.Filter.Eq(x => x.StrId, id));
    
            return await result.FirstOrDefaultAsync();
        }

    /// <summary>
    /// Asynchronously retrieves a <see cref="ServiceConfig"/> from the collection that matches the specified identifier, returning <see langword="null"/> when no matching document exists.
    /// </summary>
    /// <param name="oid">The <see cref="ObjectId"/> of the <see cref="ServiceConfig"/> to locate.</param>
    /// <returns>A <see cref="ServiceConfig"/> instance if a document with the given identifier is found; otherwise, <see langword="null"/>.</returns>
    public async Task<ServiceConfig?> FindById(ObjectId oid)
        {
            var result = await Collection.FindAsync(Builders<ServiceConfig>.Filter.Eq(x => x.Id, oid));
    
            return await result.FirstOrDefaultAsync();
        }
}