using SIGCM2.Application.Abstractions;
using SIGCM2.Application.Abstractions.Persistence;
using SIGCM2.Application.Audit;

namespace SIGCM2.Application.Auth.Logout;

public sealed class LogoutCommandHandler : ICommandHandler<LogoutCommand, LogoutResponseDto>
{
    private readonly IRefreshTokenRepository _refreshRepo;
    private readonly ISecurityEventLogger _security;
    private readonly TimeProvider _timeProvider;

    public LogoutCommandHandler(
        IRefreshTokenRepository refreshRepo,
        ISecurityEventLogger security,
        TimeProvider timeProvider)
    {
        _refreshRepo = refreshRepo;
        _security = security;
        _timeProvider = timeProvider;
    }

    public async Task<LogoutResponseDto> Handle(LogoutCommand command)
    {
        // Revoke all active tokens for the user across all families.
        // Idempotent: 0 rows affected is not an error.
        var now = _timeProvider.GetUtcNow().UtcDateTime;
        await _refreshRepo.RevokeAllActiveForUserAsync(command.UsuarioId, now);
        await _security.LogAsync("logout", "success", actorUserId: command.UsuarioId);
        return new LogoutResponseDto(true, "Sesión cerrada correctamente");
    }
}
