using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
namespace ErsatzTV.Core;
public static class VersionedAggregateExtensions
{
///
/// Optimistic-concurrency pre-check (issue #253). When the caller supplied an expected
/// version (from If-Match), fail with (→ 412)
/// if it no longer matches the loaded aggregate. An absent expectation is a force-write
/// (Phase 1 back-compat). This returns a standalone so the 412
/// is introduced AFTER the validation pipeline and never flattened to 422 by
/// (see api-conventions §7a).
///
public static Either CheckVersion(this T aggregate, Option expectedVersion)
where T : IVersionedAggregate =>
expectedVersion.Match(
Some: expected => aggregate.Version == expected
? Right(aggregate)
: Left(new PreconditionFailedError(
"The resource was modified by another request. Reload and try again.")),
None: () => Right(aggregate));
}