using adas_core.Application.Exceptions;
using adas_core.Application.Repositories.Interfaces;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Enums;
using adas_core.Domain.Models.MongoModels;
using Microsoft.Extensions.Logging;
using MongoDB.Bson;

namespace adas_core.Application.Services;

public class ServiceConfigService(
    IServiceConfigRepository serviceConfigRepository,
    ILogger<ServiceConfigService> logger)
    : IServiceConfigService
{
    private readonly ILogger<ServiceConfigService> _logger = logger;


    /// <summary>
    /// Retrieves a <see cref="ServiceConfig"/> by its identifier, attempting lookup by the string id first
    /// and falling back to an <see cref="ObjectId"/> lookup when the initial query returns no result.
    /// </summary>
    /// <param name="id">The identifier of the service configuration to retrieve. May be a string id or a valid ObjectId representation.</param>
    /// <returns>The matching <see cref="ServiceConfig"/>, or <c>null</c> when no record is found for the provided id.</returns>
    /// <exception cref="NotFoundException">Thrown when the resource cannot be found after attempting both the string id and the parsed <see cref="ObjectId"/> lookup.</exception>
    public async Task<ServiceConfig?> Get(string id)
    {
        var result = await serviceConfigRepository.FindById(id);
        if (result == null && ObjectId.TryParse(id, out var oid))
            result = await serviceConfigRepository.FindById(oid) ??
                     throw new NotFoundException(HttpEnum.ErrorMessage.NotFoundResourceMissing);

        _logger.LogDebug("ServiceConfig {id} found: {result}", id, result != null);

        return result;
    }
}