using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
namespace Helpdesk.Web.Api;
///
/// Neúspěšná odpověď API ve formátu ProblemDetails (RFC 9457). Nese stav, titulek
/// a u validačních chyb seznam chyb podle polí (klíče jsou názvy vlastností v camelCase).
///
public sealed class ApiException(HttpStatusCode statusCode, string? title, IReadOnlyDictionary errors, string? problemType = null)
: Exception(title ?? $"API vrátilo stav {(int)statusCode}.")
{
public HttpStatusCode StatusCode { get; } = statusCode;
public string? Title { get; } = title;
public string? ProblemType { get; } = problemType;
public IReadOnlyDictionary Errors { get; } = errors;
/// Text pro uživatele. API píše titulky chyb česky, kromě odpovědí bez těla (např. 429).
public string UserMessage => StatusCode switch
{
HttpStatusCode.TooManyRequests => "Příliš mnoho pokusů. Zkuste to prosím za minutu.",
_ when !string.IsNullOrWhiteSpace(Title) => Title,
HttpStatusCode.Forbidden => "K této akci nemáte oprávnění.",
HttpStatusCode.NotFound => "Záznam nebyl nalezen.",
_ => "Požadavek se nepodařilo zpracovat. Zkuste to prosím znovu.",
};
/// Chyby polí, pokud je API poslalo, jinak – pro zprávu mimo formulář.
public string AllMessages => Errors.Count == 0
? UserMessage
: string.Join(" ", Errors.Values.SelectMany(messages => messages).Distinct());
public static async Task FromResponseAsync(HttpResponseMessage response, CancellationToken ct)
{
string? title = null;
string? type = null;
Dictionary errors = new(StringComparer.OrdinalIgnoreCase);
if (response.Content.Headers.ContentType?.MediaType is { } mediaType && mediaType.Contains("json", StringComparison.OrdinalIgnoreCase))
{
try
{
var problem = await response.Content.ReadFromJsonAsync(ct);
title = problem?.Title;
type = problem?.Type;
if (problem?.Errors is { } fieldErrors)
{
foreach (var (field, messages) in fieldErrors)
errors[field] = messages;
}
}
catch (JsonException)
{
// Tělo není ProblemDetails – zůstane jen stavový kód.
}
}
return new ApiException(response.StatusCode, title, errors, type);
}
private sealed record ProblemBody(string? Title, Dictionary? Errors, string? Type);
}
internal static class ApiResponse
{
public static async Task EnsureSuccessAsync(HttpResponseMessage response, CancellationToken ct)
{
if (!response.IsSuccessStatusCode)
throw await ApiException.FromResponseAsync(response, ct);
}
public static async Task ReadAsync(HttpResponseMessage response, CancellationToken ct)
{
await EnsureSuccessAsync(response, ct);
return await response.Content.ReadFromJsonAsync(ct)
?? throw new InvalidOperationException($"API vrátilo prázdnou odpověď místo {typeof(T).Name}.");
}
}