using Big.Domain;
namespace Big.Application;
/// A zorgprofessional's request to register, in domain language. No ZGW concepts.
public sealed record SubmitRegistrationCommand(string Bsn);
///
/// The submit use case: create the aggregate (INGEDIEND), persist it,
/// then start the registratie workflow process and record its instance id. It returns as soon as
/// the process is started — opening the zaak happens later, off the request path, in the external-task
/// worker (ADR-0009). Persisting before starting the process closes the race where the worker
/// acquires the OpenZaakAanmaken job before the aggregate it correlates to exists.
///
public sealed class SubmitRegistration(IRegistrationStore store, IWorkflowClient workflow)
{
public async Task HandleAsync(SubmitRegistrationCommand command, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(command);
var registration = Registration.Submit(command.Bsn);
// Persist before starting the process so the worker can correlate the OpenZaakAanmaken
// job back to an aggregate that already exists (ADR-0009).
await store.SaveAsync(registration, ct);
var processInstanceId = await workflow.StartRegistrationProcessAsync(registration.Id, ct);
registration.RecordProcessStarted(processInstanceId);
await store.SaveAsync(registration, ct);
return registration.Id;
}
}