using Campaign_Tracker.Server.LegacyData;
namespace Campaign_Tracker.Server.ExtensionData;
///
/// Validates a by resolving it through the
/// anti-corruption layer ().
/// Each link type maps to a unique primary-key lookup, guaranteeing no ambiguity (AC #2, AC #3).
///
public sealed class LegacyLinkValidator : ILegacyLinkValidator
{
private readonly ILegacyDataAccess _legacyData;
public LegacyLinkValidator(ILegacyDataAccess legacyData)
{
_legacyData = legacyData;
}
public async Task ValidateAsync(
LegacyLinkReference reference,
CancellationToken cancellationToken = default)
{
return reference.Type switch
{
LegacyLinkType.JurisdictionJCode => await ValidateJurisdictionAsync(reference.Value, cancellationToken),
LegacyLinkType.KitId => await ValidateKitAsync(reference.Value, cancellationToken),
LegacyLinkType.ContactId => await ValidateContactAsync(reference.Value, cancellationToken),
_ => LegacyLinkValidationResult.Failure($"Unknown legacy link type '{reference.Type}'."),
};
}
private async Task ValidateJurisdictionAsync(
string jCode, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(jCode))
return LegacyLinkValidationResult.Failure("JCode is required and cannot be blank.");
var record = await _legacyData.GetJurisdictionAsync(jCode, cancellationToken);
return record is null
? LegacyLinkValidationResult.Failure(
$"No legacy jurisdiction found for JCode '{jCode}'. Verify the identifier and try again.")
: LegacyLinkValidationResult.Success();
}
private async Task ValidateKitAsync(
string rawId, CancellationToken cancellationToken)
{
if (!int.TryParse(rawId, System.Globalization.NumberStyles.Integer,
System.Globalization.CultureInfo.InvariantCulture, out var id))
return LegacyLinkValidationResult.Failure(
$"Kit identifier '{rawId}' is not a valid integer ID.");
if (id <= 0)
return LegacyLinkValidationResult.Failure(
$"Kit identifier '{rawId}' must be greater than zero.");
var record = await _legacyData.GetKitByIdAsync(id, cancellationToken);
return record is null
? LegacyLinkValidationResult.Failure(
$"No legacy kit found for ID {id}. Verify the identifier and try again.")
: LegacyLinkValidationResult.Success();
}
private async Task ValidateContactAsync(
string rawId, CancellationToken cancellationToken)
{
if (!int.TryParse(rawId, System.Globalization.NumberStyles.Integer,
System.Globalization.CultureInfo.InvariantCulture, out var id))
return LegacyLinkValidationResult.Failure(
$"Contact identifier '{rawId}' is not a valid integer ID.");
if (id <= 0)
return LegacyLinkValidationResult.Failure(
$"Contact identifier '{rawId}' must be greater than zero.");
var record = await _legacyData.GetContactByIdAsync(id, cancellationToken);
return record is null
? LegacyLinkValidationResult.Failure(
$"No legacy contact found for ID {id}. Verify the identifier and try again.")
: LegacyLinkValidationResult.Success();
}
}