using Tiku.Application.Auth;

namespace Tiku.Infrastructure.Auth;

public sealed partial class AuthService
{
    public async Task<AuthTokenPair> RefreshAsync(
        RefreshSessionRequest request,
        CancellationToken cancellationToken = default)
    {
        return await sessionStore.RotateAsync(
            request.RefreshToken, request.IpAddress, request.UserAgent, cancellationToken);
    }

    public async Task LogoutAsync(
        LogoutSessionRequest request,
        CancellationToken cancellationToken = default)
    {
        await sessionStore.RevokeFamilyAsync(request.RefreshToken, "logout", cancellationToken);
    }

    public async Task LogoutAllAsync(Guid userId, CancellationToken cancellationToken = default)
    {
        var user = await userManager.FindByIdAsync(userId.ToString())
                   ?? throw new InvalidCredentialsException();
        var stampResult = await userManager.UpdateSecurityStampAsync(user);
        if (!stampResult.Succeeded) throw new InvalidOperationException("Unable to update the user's security stamp.");

        await sessionStore.RevokeAllAsync(userId, "logout_all", cancellationToken);
    }
}