using Big.Domain;
namespace Big.Application;
///
/// Handles one acquired RegistratieVerlopen external-worker job (S-10a, ADR-0017): load the
/// registration the job correlates to and expire it to VERLOPEN โ the 30-day document-wait timer fired
/// before the documents arrived, so the case is cancelled. Pure application logic over ports; it knows
/// nothing of Flowable. The polling loop that feeds it jobs lives in Infrastructure. Mirrors
/// .
///
public sealed class ExpireRegistrationWorker(IRegistrationStore store)
{
///
/// Process the job. Idempotent and tolerant of races (ยง8.6, at-least-once delivery): a job whose
/// registration is already resolved โ a redelivered expiry (VERLOPEN), or one withdrawn/decided
/// while it waited (INGETROKKEN/INGESCHREVEN/AFGEWEZEN) โ is a no-op, so the job still completes
/// rather than throwing into a redelivery loop. Only a still-open registration is expired. An
/// unknown registration is an error: it throws, leaving the job un-completed for Flowable to redeliver.
///
public async Task HandleAsync(RegistratieVerlopenJob job, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(job);
var registration = await store.GetAsync(job.RegistrationId, ct)
?? throw new InvalidOperationException(
$"No registration {job.RegistrationId} for RegistratieVerlopen job {job.JobId}.");
// Only a still-open registration lapses; an already-resolved one (expired, or withdrawn/decided
// while it waited) is left untouched so the job can complete without violating the aggregate.
if (registration.Status is not (RegistrationStatus.Ingediend or RegistrationStatus.InBehandeling))
return;
registration.Expire();
await store.SaveAsync(registration, ct);
}
}