namespace Repository;

/// <summary>
/// 交易分类仓储接口
/// </summary>
public interface ITransactionCategoryRepository : IBaseRepository<TransactionCategory>
{
    /// <summary>
    /// 根据类型获取所有分类
    /// </summary>
    Task<List<TransactionCategory>> GetCategoriesByTypeAsync(TransactionType type);

    /// <summary>
    /// 根据名称和类型查找分类（防止重复）
    /// </summary>
    Task<TransactionCategory?> GetByNameAndTypeAsync(string name, TransactionType type);

    /// <summary>
    /// 检查分类是否被使用
    /// </summary>
    Task<bool> IsCategoryInUseAsync(long categoryId);
}

/// <summary>
/// 交易分类仓储实现
/// </summary>
public class TransactionCategoryRepository(IFreeSql freeSql) : BaseRepository<TransactionCategory>(freeSql), ITransactionCategoryRepository
{
    /// <summary>
    /// 根据类型获取所有分类
    /// </summary>
    public async Task<List<TransactionCategory>> GetCategoriesByTypeAsync(TransactionType type)
    {
        return await FreeSql.Select<TransactionCategory>()
            .Where(c => c.Type == type)
            .OrderBy(c => c.Name)
            .ToListAsync();
    }

    /// <summary>
    /// 根据名称和类型查找分类
    /// </summary>
    public async Task<TransactionCategory?> GetByNameAndTypeAsync(string name, TransactionType type)
    {
        return await FreeSql.Select<TransactionCategory>()
            .Where(c => c.Name == name && c.Type == type)
            .FirstAsync();
    }

    /// <summary>
    /// 检查分类是否被使用
    /// </summary>
    public async Task<bool> IsCategoryInUseAsync(long categoryId)
    {
        var category = await GetByIdAsync(categoryId);
        if (category == null) return false;

        var count = await FreeSql.Select<TransactionRecord>()
            .Where(r => r.Classify == category.Name && r.Type == category.Type)
            .CountAsync();

        return count > 0;
    }
}
