using Microsoft.AspNetCore.OpenApi;
using Microsoft.OpenApi;

namespace Tiku.Api.OpenApi;

internal sealed class AuthenticationOperationTagsTransformer : IOpenApiOperationTransformer
{
    private static readonly (string Prefix, string Tag)[] AuthenticationTags =
    [
        ("api/platform/auth/", "平台端-认证"),
        ("api/tenant/auth/browser/", "租户端-浏览器认证"),
        ("api/tenant/auth/", "租户端-认证"),
        ("api/student/auth/", "学生端-认证")
    ];

    public Task TransformAsync(
        OpenApiOperation operation,
        OpenApiOperationTransformerContext context,
        CancellationToken cancellationToken)
    {
        var relativePath = context.Description.RelativePath;
        if (relativePath is null) return Task.CompletedTask;

        var tag = AuthenticationTags
            .FirstOrDefault(candidate => relativePath.StartsWith(candidate.Prefix, StringComparison.OrdinalIgnoreCase))
            .Tag;
        if (tag is null) return Task.CompletedTask;

        operation.Tags ??= new HashSet<OpenApiTagReference>();
        operation.Tags.Clear();
        operation.Tags.Add(new OpenApiTagReference(tag, null!));
        return Task.CompletedTask;
    }
}
