using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json.Serialization; using Acl.Application; namespace Acl.Infrastructure; /// The only code that talks to OpenZaak's Zaken API (ADR-0001). public sealed class OpenZaakGateway(HttpClient http, OpenZaakOptions options) : IZaakGateway { public async Task OpenZaakAsync(ZaakRequest request, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(request); using var message = new HttpRequestMessage( HttpMethod.Post, new Uri(options.BaseUrl, "/zaken/api/v1/zaken")) { Content = JsonContent.Create(new ZaakDto( request.Bronorganisatie, request.Zaaktype.ToString(), request.VerantwoordelijkeOrganisatie, request.Startdatum.ToString("yyyy-MM-dd"), request.Vertrouwelijkheidaanduiding)), }; message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", ZgwToken.Mint(options.ClientId, options.Secret)); // ZRC is a geo API; it requires the CRS headers. message.Headers.Add("Accept-Crs", "EPSG:4326"); message.Content.Headers.Add("Content-Crs", "EPSG:4326"); // OpenZaak runs behind uwsgi, which rejects a chunked request body with 400. // JsonContent streams without a known length (→ Transfer-Encoding: chunked), // so buffer it first to send a Content-Length instead. Only a real OpenZaak // surfaces this — a stubbed HttpMessageHandler accepts either framing. await message.Content.LoadIntoBufferAsync(ct); using var response = await http.SendAsync(message, ct); response.EnsureSuccessStatusCode(); var created = await response.Content.ReadFromJsonAsync(ct) ?? throw new InvalidOperationException("OpenZaak returned an empty zaak response"); return new Uri(created.Url); } private sealed record ZaakDto( [property: JsonPropertyName("bronorganisatie")] string Bronorganisatie, [property: JsonPropertyName("zaaktype")] string Zaaktype, [property: JsonPropertyName("verantwoordelijkeOrganisatie")] string VerantwoordelijkeOrganisatie, [property: JsonPropertyName("startdatum")] string Startdatum, [property: JsonPropertyName("vertrouwelijkheidaanduiding")] string Vertrouwelijkheidaanduiding); private sealed record ZaakCreatedDto( [property: JsonPropertyName("url")] string Url); }