using System.Text.Json;
using ApiOPE.Contracts;

namespace ApiOPE.Security;

public static class OpeResponseWriter
{
    private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);

    public static async Task WriteErrorAsync(
        HttpResponse response,
        int statusCode,
        string message,
        string cause,
        IReadOnlyDictionary<string, string>? data,
        CancellationToken cancellationToken = default)
    {
        response.StatusCode = statusCode;
        response.ContentType = OpeMediaTypes.Error;

        var error = new OpeErrorResponse(
            statusCode,
            message,
            new OpeTypedInfo(null, null, null, cause),
            data);

        await JsonSerializer.SerializeAsync(
            response.Body,
            error,
            JsonOptions,
            cancellationToken);
    }
}
