using Distribution.Infra.UoW; namespace Distribution.Features.Brand; public class BrandService(IBrandRepository repo, IUnitOfWork uow) { public async Task> GetAllAsync() => (await repo.GetAllAsync()) .Where(b => b.IsActive) .Select(b => new BrandResponse(b.Id, b.Name, b.IsActive, b.CreatedAt)) .ToList(); public async Task GetByIdAsync(Guid id) { var brand = await repo.GetByIdAsync(id); if (brand is null || !brand.IsActive) return null; return new BrandResponse(brand.Id, brand.Name, brand.IsActive, brand.CreatedAt); } public async Task CreateAsync(CreateBrandRequest request, CancellationToken ct = default) { var brand = new Models.Brand { Name = request.Name }; await uow.BeginAsync(ct); try { await repo.AddAsync(brand); await uow.CommitAsync(ct); } catch { await uow.RollbackAsync(ct); throw; } return new BrandResponse(brand.Id, brand.Name, brand.IsActive, brand.CreatedAt); } public async Task UpdateAsync(Guid id, UpdateBrandRequest request, CancellationToken ct = default) { var brand = await repo.GetByIdAsync(id); if (brand is null || !brand.IsActive) return null; if (brand.ExternalErpId.HasValue) return null; brand.Name = request.Name; await uow.BeginAsync(ct); try { repo.Update(brand); await uow.CommitAsync(ct); } catch { await uow.RollbackAsync(ct); throw; } return new BrandResponse(brand.Id, brand.Name, brand.IsActive, brand.CreatedAt); } public async Task DeleteAsync(Guid id, CancellationToken ct = default) { var brand = await repo.GetByIdAsync(id); if (brand is null || !brand.IsActive) return false; if (brand.ExternalErpId.HasValue) return false; if (await repo.HasActiveItemsAsync(id)) return false; await uow.BeginAsync(ct); try { repo.Remove(brand); await uow.CommitAsync(ct); } catch { await uow.RollbackAsync(ct); throw; } return true; } }