using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.OpenApi;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Nodes;

namespace OnlineSalesAutoCrop.CoreAPI.Models.Global
{
	/// <summary>
	/// Represents the Swagger/Swashbuckle operation filter used to document the implicit API version parameter.
	/// </summary>
	/// <remarks>This <see cref="IOperationFilter"/> is only required due to bugs in the <see cref="SwaggerGenerator"/>.
	/// Once they are fixed and published, this class can be removed.</remarks>
	public class SwaggerDefaultValues : IOperationFilter
	{
		/// <inheritdoc />
		public void Apply(OpenApiOperation operation, OperationFilterContext context)
		{
			var apiDescription = context.ApiDescription;

			// REF: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1752#issue-663991077
			foreach (var responseType in context.ApiDescription.SupportedResponseTypes)
			{
				// REF: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/b7cf75e7905050305b115dd96640ddd6e74c7ac9/src/Swashbuckle.AspNetCore.SwaggerGen/SwaggerGenerator/SwaggerGenerator.cs#L383-L387
				var responseKey = responseType.IsDefaultResponse ? "default" : responseType.StatusCode.ToString();
				var response = operation.Responses[responseKey];

				foreach (var contentType in response.Content.Keys)
				{
					if (!responseType.ApiResponseFormats.Any(x => x.MediaType == contentType))
					{
						response.Content.Remove(contentType);
					}
				}
			}

			if (operation.Parameters == null)
			{
				return;
			}

			foreach (OpenApiParameter parameter in operation.Parameters.OfType<OpenApiParameter>())
			{
				var description = apiDescription.ParameterDescriptions.First(p => p.Name == parameter.Name);
				parameter.Description ??= description.ModelMetadata?.Description;

				if (parameter.Schema is OpenApiSchema openApiSchema)
				{
					if (parameter.Schema.Default == null && description.DefaultValue != null &&
					 description.DefaultValue is not DBNull && description.ModelMetadata is ModelMetadata modelMetadata)
					{
						var json = JsonSerializer.Serialize(description.DefaultValue, modelMetadata.ModelType);
						var element = JsonSerializer.Deserialize<JsonElement>(json);
						openApiSchema.Default = JsonValue.Create(element);
					}

					parameter.Required |= description.IsRequired;
				}
			}
		}
	}
}
