using System.Net;
using System.Text.Json;

namespace DbFirst.BlazorWebApp.Services;

internal sealed class ProblemDetailsDto
{
    public string? Type { get; set; }
    public string? Title { get; set; }
    public string? Detail { get; set; }
}

internal static class ApiClientHelper
{
    public static async Task<string> ReadErrorAsync(HttpResponseMessage response)
    {
        string? problemTitle = null;
        string? problemDetail = null;

        try
        {
            var problem = await response.Content.ReadFromJsonAsync<ProblemDetailsDto>();
            if (problem != null)
            {
                problemTitle = problem.Title;
                problemDetail = problem.Detail ?? problem.Type;
            }
        }
        catch (JsonException)
        {
            // Ignoriere Fehler beim Lesen der Problem-Details, da sie optional sind
        }
        catch (NotSupportedException)
        {
            // Ignoriere Fehler beim Lesen der Problem-Details, da sie optional sind
        }

        var status = response.StatusCode;
        var reason = response.ReasonPhrase;
        var body = await response.Content.ReadAsStringAsync();

        string? detail = problemDetail;
        if (string.IsNullOrWhiteSpace(detail) && !string.IsNullOrWhiteSpace(body))
            detail = body;

        return status switch
        {
            HttpStatusCode.BadRequest => $"Eingabe ungültig{FormatSuffix(problemTitle, detail, reason)}",
            HttpStatusCode.NotFound => $"Nicht gefunden{FormatSuffix(problemTitle, detail, reason)}",
            HttpStatusCode.Conflict => $"Konflikt{FormatSuffix(problemTitle, detail, reason)}",
            HttpStatusCode.Unauthorized => $"Nicht autorisiert{FormatSuffix(problemTitle, detail, reason)}",
            HttpStatusCode.Forbidden => $"Nicht erlaubt{FormatSuffix(problemTitle, detail, reason)}",
            HttpStatusCode.InternalServerError => $"Serverfehler{FormatSuffix(problemTitle, detail, reason)}",
            _ => $"Fehler {(int)status} {reason ?? string.Empty}{FormatSuffix(problemTitle, detail, reason)}"
        };
    }

    private static string FormatSuffix(string? title, string? detail, string? reason)
    {
        var parts = new List<string>();
        if (!string.IsNullOrWhiteSpace(title)) parts.Add(title);
        if (!string.IsNullOrWhiteSpace(detail)) parts.Add(detail);
        if (parts.Count == 0 && !string.IsNullOrWhiteSpace(reason)) parts.Add(reason);
        if (parts.Count == 0) return string.Empty;
        return ": " + string.Join(" | ", parts);
    }
}