using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using Idoklad.Controllers;
using Idoklad.Credentials;

namespace Idoklad.Infrastructure;

/// <summary>
/// Documents the per-request credential headers in Swagger for every operation that talks to
/// iDoklad. The headers are marked optional because the service can fall back to environment
/// defaults, but the description makes the requirement and secret handling explicit.
/// </summary>
public sealed class CredentialHeadersOperationFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        // Metadata endpoints (health/version/status) do not talk to iDoklad and need no credentials.
        if (context.MethodInfo.DeclaringType == typeof(MetaController))
        {
            return;
        }

        operation.Parameters ??= new List<OpenApiParameter>();

        AddHeader(operation, CredentialConstants.ClientIdHeader,
            "iDoklad OAuth2 ClientId (client credentials flow). Overrides the IDOKLAD_CLIENT_ID environment default. Required if no environment default is configured.");

        AddHeader(operation, CredentialConstants.ClientSecretHeader,
            "iDoklad OAuth2 ClientSecret (SENSITIVE). Must be sent in this header over TLS only — never in the URL or body. Overrides the IDOKLAD_CLIENT_SECRET environment default. Required if no environment default is configured.");

        AddHeader(operation, CredentialConstants.ApplicationIdHeader,
            "iDoklad ApplicationId from the developer portal. Overrides the IDOKLAD_APPLICATION_ID environment default. Required by the client credentials flow if no environment default is configured.");

        AddHeader(operation, CredentialConstants.LanguageHeader,
            "Optional response language override for the iDoklad API: Cz, Sk or En.", example: "Cz");
    }

    private static void AddHeader(OpenApiOperation operation, string name, string description, string? example = null)
    {
        operation.Parameters.Add(new OpenApiParameter
        {
            Name = name,
            In = ParameterLocation.Header,
            Required = false,
            Description = description,
            Schema = new OpenApiSchema
            {
                Type = "string",
                Example = example is null ? null : new OpenApiString(example),
            },
        });
    }
}
