using Microsoft.EntityFrameworkCore;
using OmsorgCore.Application.Abstractions;
using OmsorgCore.Domain.Entities;
using OmsorgCore.Infrastructure.Persistence;

namespace OmsorgCore.Infrastructure.Repositories;

public class LoginAttemptRepository : ILoginAttemptRepository
{
    private readonly OmsorgCoreDbContext _db;

    public LoginAttemptRepository(OmsorgCoreDbContext db)
    {
        _db = db;
    }

    public Task<int> CountRecentFailuresAsync(string ipAddress, DateTime since, CancellationToken cancellationToken = default)
        => _db.LoginAttempts.CountAsync(
            a => a.IpAddress == ipAddress && !a.Succeeded && a.AttemptedAt > since, cancellationToken);

    public async Task AddAsync(LoginAttempt attempt, CancellationToken cancellationToken = default)
        => await _db.LoginAttempts.AddAsync(attempt, cancellationToken);

    public async Task ClearFailuresAsync(string ipAddress, CancellationToken cancellationToken = default)
    {
        var failures = await _db.LoginAttempts
            .Where(a => a.IpAddress == ipAddress && !a.Succeeded)
            .ToListAsync(cancellationToken);
        _db.LoginAttempts.RemoveRange(failures);
    }

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