namespace Monitoring.SchemaTransformers;

using Microsoft.AspNetCore.OpenApi;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Serilog;

public sealed class EnumSchemaTransformer : IOpenApiSchemaTransformer
{
	public Task TransformAsync(
		OpenApiSchema schema,
		OpenApiSchemaTransformerContext context,
		CancellationToken cancellationToken
	)
	{
		var enumType = context.JsonTypeInfo.Type;
		var underlying = Nullable.GetUnderlyingType(enumType);
		enumType = underlying ?? enumType;

		if (!enumType.IsEnum)
		{
			return Task.CompletedTask;
		}

		var enumValues = Enum.GetValues(enumType);
		var enumNames = Enum.GetNames(enumType);

		// если был Nullable<Enum>, помечаем nullable
		if (underlying is not null)
		{
			schema.Nullable = true;
		}

		schema.Type = "integer";
		schema.Format = "int32";
		schema.Enum = enumValues
			.Cast<object>()
			.Select(v => (IOpenApiAny)new OpenApiInteger(Convert.ToInt32(v)))
			.ToList();

		var enumNamesArray = new OpenApiArray();
		foreach (var name in enumNames)
		{
			enumNamesArray.Add(new OpenApiString(name));
		}

		schema.Extensions["x-enumNames"] = enumNamesArray;

		return Task.CompletedTask;
	}
}

