namespace WebApi.Test.Repository;

public class BudgetRepositoryTest : TransactionTestBase
{
    private readonly IBudgetRepository _repository;
    private readonly ITransactionRecordRepository _transactionRepository;

    public BudgetRepositoryTest()
    {
        _repository = new BudgetRepository(FreeSql);
        _transactionRepository = new TransactionRecordRepository(FreeSql);
    }

    [Fact]
    public async Task GetCurrentAmountAsync_计算预算金额_Test()
    {
        // Arrange
        // 插入一些交易记录
        await _transactionRepository.AddAsync(CreateExpense(100, classify: "餐饮")); // A
        await _transactionRepository.AddAsync(CreateExpense(200, classify: "交通")); // B
        await _transactionRepository.AddAsync(CreateExpense(50, classify: "餐饮"));  // C
        await _transactionRepository.AddAsync(CreateIncome(1000)); // 收入，不应计入支出预算

        var budget = new BudgetRecord
        {
            Limit = 2000,
            Category = BudgetCategory.Expense,
            SelectedCategories = "餐饮,购物", // Only 餐饮 matches
            Name = "日常开销"
        };

        var startDate = DateTime.Now.AddDays(-1);
        var endDate = DateTime.Now.AddDays(1);

        // Act
        var amount = await _repository.GetCurrentAmountAsync(budget, startDate, endDate);

        // Assert
        // Should sum A+C = -150. But wait, transaction amounts for expense are negative in CreateExpense?
        // Let's check CreateExpense: return CreateTestRecord(-amount, ...);
        // So actual stored values are -100, -200, -50.
        // SumAsync sums them up. Result should be -150.
        amount.Should().Be(-150);
    }

    [Fact]
    public async Task UpdateBudgetCategoryNameAsync_更新分类名称_Test()
    {
        // Arrange
        await _repository.AddAsync(new BudgetRecord { Name = "B1", SelectedCategories = "餐饮,交通", Category = BudgetCategory.Expense });
        await _repository.AddAsync(new BudgetRecord { Name = "B2", SelectedCategories = "餐饮", Category = BudgetCategory.Expense });
        await _repository.AddAsync(new BudgetRecord { Name = "B3", SelectedCategories = "住宿", Category = BudgetCategory.Expense });

        // Act
        // 将 "餐饮" 更新为 "美食"
        await _repository.UpdateBudgetCategoryNameAsync("餐饮", "美食", TransactionType.Expense);

        // Assert
        var all = await _repository.GetAllAsync();
        var b1_updated = all.First(b => b.Name == "B1");
        b1_updated.SelectedCategories.Should().Contain("美食");
        b1_updated.SelectedCategories.Should().NotContain("餐饮");
        
        var b2_updated = all.First(b => b.Name == "B2");
        b2_updated.SelectedCategories.Should().Be("美食");
    }
}
