using Pgo.Backend.Data.Models;
using Pgo.Backend.Helpers;
using Pgo.Backend.Interfaces;
using System.Collections.Concurrent;

namespace Pgo.Backend.Services;

public class StelselNodeService(ILogger<StelselNodeService> logger, IStelselNodeApiClient stelselnodeApiClient) : IStelselNodeService
{
    private readonly ILogger<StelselNodeService> _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    private readonly IStelselNodeApiClient _stelselnodeApiClient = stelselnodeApiClient ?? throw new ArgumentNullException(nameof(stelselnodeApiClient));
    private const string _stelselnodeVersion = "2.3.0"; // Experimental ZAL with support for type Koppelvlak ADP (aanbieder persoonsdomein).
    private const string _systeemrolcode = "MM-3.0-PLR-FHIR"; // Verzamelen Documenten 3.0 (MM-3.0-PLR-FHIR)

    public ConcurrentBag<StelselNodeProvider> Zorgaanbieders { get; private set; } = new();

    public List<StelselNodeProvider> GetZorgaanbieders()
    {
        return Zorgaanbieders.ToList();
    }

    public async Task UpdateStelselNodeListsAsync(CancellationToken cancellationToken)
    {
        try
        {
            var resultZal = await _stelselnodeApiClient.GetZalAsync(_stelselnodeVersion, cancellationToken);
            if (resultZal.IsSuccessStatusCode)
            {
                List<StelselNodeProvider> dvas = ZalConverter.ConvertZalToDvaListHumanReadable(resultZal.Content, _systeemrolcode);
                _logger.LogInformation("Found {count} DVAs in ZAL.", dvas.Count);
                Zorgaanbieders.Clear();
                dvas.ForEach(dva => Zorgaanbieders.Add(dva));                
            }
            else
            {
                _logger.LogError("Failed to get ZAL from stelselnode.");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError("Failed to get ZAL from stelselnode. Exception Message={message}", ex.Message);
        }
    }
}
