using System.Net.Http.Json;
using System.Text.Json;
namespace EnvelopeGenerator.Server.Client.Services;
///
/// Fetches and caches the CustomImages configuration (signFLOW + company logos)
/// from GET /api/CustomImages.
///
/// Config changes rarely (deployment-time only), so results are cached in-memory
/// for the lifetime of the service (WASM app session). No TTL needed.
///
public class CustomImagesService(IHttpClientFactory clientFactory)
{
private static readonly JsonSerializerOptions _json = new(JsonSerializerDefaults.Web);
private const string Endpoint = "/api/CustomImages";
private CustomImagesDto? _cached;
///
/// Returns logo configuration. Fetches once from server; all subsequent calls
/// are served from memory with zero network overhead.
/// Returns defaults (empty Src) on auth failure (401) — components must handle gracefully.
///
public async Task GetAsync(CancellationToken ct = default)
{
if (_cached is not null)
return _cached;
try
{
var client = clientFactory.CreateClient("EnvelopeGenerator.Server");
var response = await client.GetAsync(Endpoint, ct);
if (!response.IsSuccessStatusCode)
{
// Not authenticated yet (login page) — return defaults silently.
_cached = new CustomImagesDto();
return _cached;
}
_cached = await response.Content.ReadFromJsonAsync(_json, ct)
?? new CustomImagesDto();
return _cached;
}
catch (Exception)
{
// Network error or server unavailable — return defaults so UI still renders.
return new CustomImagesDto();
}
}
/// Call after logout to force re-fetch on next login.
public void Invalidate() => _cached = null;
}