namespace WebApi.Test.Repository;

public class TransactionPeriodicRepositoryTest : TransactionTestBase
{
    private readonly ITransactionPeriodicRepository _repository;

    public TransactionPeriodicRepositoryTest()
    {
        _repository = new TransactionPeriodicRepository(FreeSql);
    }

    [Fact]
    public async Task GetPendingPeriodicBillsAsync_获取待执行账单_Test()
    {
        // 应该执行的：NextExecuteTime <= Now
        await _repository.AddAsync(new TransactionPeriodic { Reason = "Bill1", NextExecuteTime = DateTime.Now.AddDays(-1), IsEnabled = true });
        
        // 不该执行的：NextExecuteTime > Now
        await _repository.AddAsync(new TransactionPeriodic { Reason = "Bill2", NextExecuteTime = DateTime.Now.AddDays(1), IsEnabled = true });
        
        // 不该执行的：未激活
        await _repository.AddAsync(new TransactionPeriodic { Reason = "Bill3", NextExecuteTime = DateTime.Now.AddDays(-1), IsEnabled = false });

        var results = await _repository.GetPendingPeriodicBillsAsync();
        results.Should().HaveCount(1);
        results.First().Reason.Should().Be("Bill1");
    }

    [Fact]
    public async Task UpdateExecuteTimeAsync_更新执行时间_Test()
    {
        var bill = new TransactionPeriodic { Reason = "Bill", NextExecuteTime = DateTime.Now };
        await _repository.AddAsync(bill);

        var last = DateTime.Now;
        var next = DateTime.Now.AddMonths(1);

        await _repository.UpdateExecuteTimeAsync(bill.Id, last, next);

        var updated = await _repository.GetByIdAsync(bill.Id);
        updated!.LastExecuteTime.Should().BeCloseTo(last, TimeSpan.FromSeconds(1));
        updated.NextExecuteTime.Should().BeCloseTo(next, TimeSpan.FromSeconds(1));
    }
}
