namespace Khaemhat.Fiscal.Abstractions;
///
/// The country packs registered at start-up, found by country code. The composition root registers the concrete packs;
/// application code receives this catalog and never names a country's implementation.
///
public sealed class FiscalPackCatalog
{
private readonly Dictionary _byCountry;
/// Creates the catalog.
/// The packs; two packs for the same country are a configuration error.
public FiscalPackCatalog(IEnumerable packs)
{
ArgumentNullException.ThrowIfNull(packs);
_byCountry = new Dictionary(StringComparer.OrdinalIgnoreCase);
foreach (var pack in packs)
{
if (!_byCountry.TryAdd(pack.CountryCode, pack))
{
throw new ArgumentException($"Two fiscal packs for country '{pack.CountryCode}'.", nameof(packs));
}
}
Packs = [.. _byCountry.Values.OrderBy(p => p.CountryCode, StringComparer.Ordinal)];
}
/// Every registered pack, by country code.
public IReadOnlyList Packs { get; }
/// The pack of a country.
/// ISO 3166-1 alpha-2 code, case-insensitive.
/// The pack.
/// No pack for that country.
public IFiscalPack ForCountry(string? countryCode) =>
TryForCountry(countryCode, out var pack) ? pack : throw new FiscalPackNotFoundException(countryCode ?? string.Empty);
/// The pack of a country, if registered.
/// ISO 3166-1 alpha-2 code, case-insensitive.
/// The pack, when found.
/// Whether a pack was found.
public bool TryForCountry(string? countryCode, out IFiscalPack pack)
{
if (!string.IsNullOrWhiteSpace(countryCode) && _byCountry.TryGetValue(countryCode.Trim(), out var found))
{
pack = found;
return true;
}
pack = null!;
return false;
}
}
/// No fiscal pack is registered for the country of the company.
public sealed class FiscalPackNotFoundException : Exception
{
/// Creates the exception.
public FiscalPackNotFoundException()
: this(string.Empty)
{
}
/// Creates the exception.
/// The country without a pack.
public FiscalPackNotFoundException(string countryCode)
: base($"No fiscal pack for country '{countryCode}'.") => CountryCode = countryCode;
/// Creates the exception.
/// The message.
/// The cause.
public FiscalPackNotFoundException(string message, Exception innerException)
: base(message, innerException) => CountryCode = string.Empty;
/// The country without a pack.
public string CountryCode { get; }
}