using e_suite.API.Common.repository;
using e_suite.Database.Core;
using e_suite.Database.Core.Tables.Sentinel;
using Microsoft.EntityFrameworkCore;

namespace e_suite.Service.Sentinel.Repository;

public class SentinelRepository : ISentinelRepository
{
    private readonly IEsuiteDatabaseDbContext _esuiteDatabaseDbContext;

    public SentinelRepository(IEsuiteDatabaseDbContext esuiteDatabaseDbContext)
    {
        _esuiteDatabaseDbContext = esuiteDatabaseDbContext;
    }

    public async Task AddFailedAccessAttempt(FailedAccessAttempt failedLoginAttempt, CancellationToken cancellationToken)
    {
        await _esuiteDatabaseDbContext.FailedAccessAttempts.AddAsync(failedLoginAttempt, cancellationToken);
        await _esuiteDatabaseDbContext.NoAuditSaveChangesAsync(cancellationToken);
    }

    public async Task<int> GetAccessAttemptsSince(string ipAddress, DateTimeOffset earliestAttemptTime, CancellationToken cancellationToken)
    {
        return await _esuiteDatabaseDbContext.FailedAccessAttempts.CountAsync(x =>
            x.IPAddress == ipAddress && x.AttemptedTime >= earliestAttemptTime, cancellationToken);
    }

    public async Task DeleteAccessAttemptsBefore(DateTimeOffset earliestAttemptTime)
    {
        var itemsToRemove = _esuiteDatabaseDbContext.FailedAccessAttempts.Where(x => x.AttemptedTime < earliestAttemptTime);
        _esuiteDatabaseDbContext.FailedAccessAttempts.RemoveRange(itemsToRemove);
        await _esuiteDatabaseDbContext.NoAuditSaveChangesAsync();
    }
}