using Microsoft.Extensions.Configuration;

namespace LazyBear.MCP.Services.GitLab;

/// <summary>
/// Провайдер GitLab клиента для DI
/// </summary>
public sealed class GitLabClientProvider : IDisposable
{
    private readonly IConfiguration _config;
    private readonly object _locker;
    private GitLabApiClient? _client;
    public string? InitializationError { get; private set; }

    /// <summary>
    /// Конструктор
    /// </summary>
    /// <param name="config">Конфигурация приложения</param>
    public GitLabClientProvider(IConfiguration config)
    {
        _config = config;
        _locker = new object();
    }

    private void SetError(string message)
    {
        InitializationError = message;
    }

    /// <summary>
    /// Создание клиента
    /// </summary>
    public GitLabApiClient? GetClient()
    {
        var baseUrl = _config["GitLab:Url"];
        if (string.IsNullOrEmpty(baseUrl))
        {
            SetError("GitLab:Url не настроен в конфигурации.");
            return null;
        }

        lock (_locker)
        {
            if (_client == null)
            {
                _client = new GitLabApiClient(baseUrl);
            }
            return _client;
        }
    }

    public void Dispose()
    {
        _client?.Dispose();
    }
}
