using Hl7.Fhir.Model;
using Hl7.Fhir.Serialization;
using Microsoft.AspNetCore.Mvc.Formatters;
using System.Text;
using Task = System.Threading.Tasks.Task;

public class FhirJsonOutputFormatter : TextOutputFormatter
{
    public FhirJsonOutputFormatter()
    {
        SupportedMediaTypes.Add("application/fhir+json");
        SupportedMediaTypes.Add("application/json");
        SupportedEncodings.Add(Encoding.UTF8);
    }

    protected override bool CanWriteType(Type? type)
    {
        return type != null && typeof(Resource).IsAssignableFrom(type);
    }

    public override async Task WriteResponseBodyAsync(
        OutputFormatterWriteContext context, Encoding selectedEncoding)
    {
        var resource = context.Object as Resource;
        if (resource is null) return;

        var serializer = new FhirJsonSerializer(new SerializerSettings { Pretty = true });
        var json = serializer.SerializeToString(resource);
        await context.HttpContext.Response.WriteAsync(json, selectedEncoding);
    }
}