using System.Text.Json; using Admin.NET.Plugin.AiDOP.DataPlatform.Core; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress; [ApiController] [ApiExplorerSettings(IgnoreApi = true)] [Route("api/DataPlatform/internal/purchase-handoff")] [NonUnify] [Authorize(AuthenticationSchemes = MdpPurchaseHandoffAuthenticationHandler.SchemeName)] public sealed class MdpPurchaseHandoffController(MdpPurchaseHandoffService handoff) : ControllerBase { private static readonly JsonSerializerOptions ResponseJson = new(JsonSerializerDefaults.Web); [HttpPost] [RequestSizeLimit(1024 * 1024)] [Consumes("application/json")] public async Task Receive(CancellationToken cancellationToken) { try { var package = await JsonSerializer.DeserializeAsync(Request.Body, ResponseJson, cancellationToken); if (package?.Items is null || package.ComputeDigest() != Request.Headers[PurchaseDispatchProof.DigestHeader].ToString()) return ResponseBody(400, new { code = "HANDOFF_DIGEST_MISMATCH" }); var receipt = await handoff.ReceiveAsync(package, cancellationToken); return ResponseBody(StatusCodes.Status200OK, receipt); } catch (JsonException) { return ResponseBody(400, new { code = "HANDOFF_INVALID_PACKAGE" }); } catch (MdpIngestHttpException error) { return ResponseBody(error.StatusCode, new { code = error.Code, traceId = HttpContext.TraceIdentifier }); } } [HttpGet("{batch:guid}")] public async Task FindReceipt(Guid batch, CancellationToken token) { try { var receipt = await handoff.FindReceiptAsync(batch, Request.Headers[PurchaseDispatchProof.DigestHeader].ToString(), token); return receipt is null ? NotFound() : ResponseBody(200, receipt); } catch (MdpIngestHttpException error) { return ResponseBody(error.StatusCode, new { code = error.Code }); } } private static ContentResult ResponseBody(int status, object body) => new() { StatusCode = status, ContentType = "application/json; charset=utf-8", Content = JsonSerializer.Serialize(body, ResponseJson) }; }