using MassTransit;
using Tiku.Application.Security;
using Tiku.Contracts;

namespace Tiku.Infrastructure.Messaging;

[ConsumerAuthorizationMetadata(
    "system", "security-state", CapabilityOperation.Read, "security.invalidation.apply")]
internal sealed class SecurityStateChangedConsumer(IRedisSecurityStore redisSecurityStore) :
    IConsumer<AuthorizationStateChangedV1>,
    IConsumer<TenantCapabilityChangedV1>,
    IConsumer<MembershipLifecycleChangedV1>
{
    public Task Consume(ConsumeContext<AuthorizationStateChangedV1> context) =>
        redisSecurityStore.SetInvalidationVersionAsync(
            "authorization", context.Message.TenantId, context.Message.UserId,
            context.Message.Version, context.CancellationToken);

    public Task Consume(ConsumeContext<TenantCapabilityChangedV1> context) =>
        redisSecurityStore.SetInvalidationVersionAsync(
            $"capability-{context.Message.ModuleCode}", context.Message.TenantId, null,
            context.Message.Version, context.CancellationToken);

    public Task Consume(ConsumeContext<MembershipLifecycleChangedV1> context) =>
        redisSecurityStore.SetInvalidationVersionAsync(
            "membership", context.Message.TenantId, context.Message.UserId,
            context.Message.OccurredAt.ToUnixTimeMilliseconds(), context.CancellationToken);
}
