namespace Monitoring.SchemaTransformers;

using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.OpenApi.Models;
using Monitoring.Features.Analytics;
using Serilog;

/// <summary>
/// Чинит схему счетчика событий.
/// TODO: Убрать, когда починят генератор.
/// </summary>
public sealed class FixCountOfEventsSchemaTransformer : IOpenApiSchemaTransformer
{
	public Task TransformAsync(
		OpenApiSchema schema,
		OpenApiSchemaTransformerContext context,
		CancellationToken cancellationToken
	)
	{
		// Чиним только нужный тип
		if (context.JsonTypeInfo?.Type == typeof(CountOfEventsResponseModel))
		{
			var itemRef = new OpenApiSchema
			{
				Reference = new OpenApiReference
				{
					Type = ReferenceType.Schema,
					Id = nameof(CountOfEventsItemResponseModel),
				},
			};

			Log.Information(
				"Fixing count of events schema: {Schema}",
				string.Join(", ", schema.Properties.Select(x => x.Key))
			);

			foreach (var key in new[] { "alarms", "faults", "operatorActions" })
			{
				if (schema.Properties.TryGetValue(key, out var prop))
				{
					prop.Items = itemRef;
				}
			}
		}

		return Task.CompletedTask;
	}
}
