using General_Ledger_Service.DTOs.CostCenters; using General_Ledger_Service.Infra; using General_Ledger_Service.Interfaces.Repositories; using General_Ledger_Service.Models; using Microsoft.EntityFrameworkCore; namespace General_Ledger_Service.Repositories { public class CostCenterRepository(AppDBContext context) : ICostCenterRepository { private readonly AppDBContext _context = context; public Task GetByIdAsync(long costCenterId) => RepositoryHelpers.GetByIdAsync(_context.CostCenters, costCenterId); public async Task GetByCodeAsync(string code) => await _context.CostCenters.FirstOrDefaultAsync(c => c.Code == code); public async Task GetAncestorDepthAsync(long parentCostCenterId) => RecursiveTreeQueries.GetAncestorDepth(await LoadTreeRowsAsync(), parentCostCenterId); public async Task GetAncestorBreadcrumbAsync(long costCenterId) => RecursiveTreeQueries.GetAncestorBreadcrumb(await LoadTreeRowsAsync(), costCenterId); public async Task> GetDescendantTreeAsync(long costCenterId) { var rows = RecursiveTreeQueries.GetDescendantTree(await LoadTreeRowsAsync(), costCenterId); return [.. rows.Select(r => new CostCenterTreeNode { CostCenterId = r.Id, Code = r.Code, Name = r.Name, ParentCostCenterId = r.ParentId, Depth = r.Depth })]; } public Task AddAsync(CostCenter costCenter) => RepositoryHelpers.AddAsync(_context.CostCenters, costCenter); private async Task> LoadTreeRowsAsync() => await _context.CostCenters.AsNoTracking() .Select(c => new RecursiveTreeQueries.TreeRow { Id = c.CostCenterId, Code = c.Code, Name = c.Name, ParentId = c.ParentCostCenterId }) .ToListAsync(); } }