using e_suite.API.Common.repository;
using e_suite.Database.Audit;
using e_suite.Database.Core;
using FailedAccessAttempt = e_suite.Database.Core.Tables.Sentinel.FailedAccessAttempt;

namespace e_suite.Modules.BlockedIPsManager.Repository;

public class BlockedIPsManagerRepository : RepositoryBase, IBlockedIPsManagerRepository
{
    public BlockedIPsManagerRepository(IEsuiteDatabaseDbContext databaseDbContext) : base(databaseDbContext)
    {
    }

    public IQueryable<FailedAccessAttempt> GetBlockedIPs(DateTimeOffset earliestAttemptTime)
    {
        return DatabaseDbContext.FailedAccessAttempts
            .Where(x => x.AttemptedTime >= earliestAttemptTime);
    }
    
    public async Task UnBlockIP(AuditUserDetails auditUserDetails, string ipAddress, CancellationToken cancellationToken)
    {
        var failedAccessAttempts = DatabaseDbContext.FailedAccessAttempts.Where(x => x.IPAddress == ipAddress);
        DatabaseDbContext.FailedAccessAttempts.RemoveRange(failedAccessAttempts);
        await DatabaseDbContext.SaveChangesAsync(auditUserDetails, cancellationToken);
    }
}
