// <copyright file="JsonDefaultStringEnumConverterFactory.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>

#pragma warning disable SA1309 // Variables should not begin with underscore

namespace Jellyfin.Extensions.Json.Converters
{
    using System;
    using System.ComponentModel;
    using System.Reflection;
    using System.Text.Json;
    using System.Text.Json.Serialization;

    /// <summary>
    /// Utilizes the JsonStringEnumConverter and sets a default value if not provided.
    /// </summary>
    public class JsonDefaultStringEnumConverterFactory : JsonConverterFactory
    {
        private static readonly JsonStringEnumConverter _baseConverterFactory = new();

        /// <inheritdoc />
        public override bool CanConvert(Type typeToConvert)
        {
            return _baseConverterFactory.CanConvert(typeToConvert)
                   && typeToConvert.IsDefined(typeof(DefaultValueAttribute));
        }

        /// <inheritdoc />
        public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options)
        {
            var baseConverter = _baseConverterFactory.CreateConverter(typeToConvert, options);
            var converterType = typeof(JsonDefaultStringEnumConverter<>).MakeGenericType(typeToConvert);

            return (JsonConverter?)Activator.CreateInstance(converterType, baseConverter);
        }
    }
}
