using Backend.Data;
using Backend.Domain;
using Microsoft.EntityFrameworkCore;

namespace Backend.Repositories;

public sealed class UserSessionRepository(AwardsDbContext dbContext) : IUserSessionRepository
{
    public Task<UserSession?> GetActiveByTokenAsync(string token, CancellationToken cancellationToken = default) =>
        dbContext.UserSessions.FirstOrDefaultAsync(
            item => item.SessionToken == token && item.IsActive,
            cancellationToken);

    public Task<int> CountRecentSessionsFromIpAsync(string ipAddress, DateTimeOffset since, CancellationToken cancellationToken = default) =>
        dbContext.UserSessions.CountAsync(
            item => item.CreatedFromIp == ipAddress && item.CreatedAt >= since,
            cancellationToken);

    public void Add(UserSession session) => dbContext.UserSessions.Add(session);

    public Task SaveChangesAsync(CancellationToken cancellationToken = default) =>
        dbContext.SaveChangesAsync(cancellationToken);
}
