using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace StellaOps.Scanner.WebService.Infrastructure;

internal static class ProblemResultFactory
{
    private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
    {
        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
    };

    public static IResult Create(
        HttpContext context,
        string type,
        string title,
        int statusCode,
        string? detail = null,
        IDictionary<string, object?>? extensions = null)
    {
        ArgumentNullException.ThrowIfNull(context);
        ArgumentException.ThrowIfNullOrWhiteSpace(type);
        ArgumentException.ThrowIfNullOrWhiteSpace(title);

        var traceId = Activity.Current?.TraceId.ToString() ?? context.TraceIdentifier;

        var problem = new ProblemDetails
        {
            Type = type,
            Title = title,
            Detail = detail,
            Status = statusCode,
            Instance = context.Request.Path
        };

        problem.Extensions["traceId"] = traceId;
        if (extensions is not null)
        {
            foreach (var entry in extensions)
            {
                problem.Extensions[entry.Key] = entry.Value;
            }
        }

        var payload = JsonSerializer.Serialize(problem, JsonOptions);
        return Results.Content(payload, "application/problem+json", Encoding.UTF8, statusCode);
    }
}
