using SCM.Application.Common; using SCM.Application.Qualidade.Dtos; using SCM.Domain.Qualidade; using SCM.Shared.Exceptions; namespace SCM.Application.Qualidade; public sealed class AgenteService : IAgenteService { private readonly IAgenteRepository _repository; private readonly IUnitOfWork _unitOfWork; public AgenteService(IAgenteRepository repository, IUnitOfWork unitOfWork) { _repository = repository; _unitOfWork = unitOfWork; } public async Task> GetAllAsync(CancellationToken ct = default) { var itens = await _repository.GetAllAsync(ct); return itens.Select(x => x.Agente.ToResponse(x.QtdProgramacoes)).ToList(); } public async Task GetByIdAsync(Guid id, CancellationToken ct = default) { var agente = await _repository.GetByIdAsync(id, ct) ?? throw new NotFoundException($"Agente {id} não encontrado."); var qtd = await _repository.ContarProgramacoesAsync(id, ct); return agente.ToResponse(qtd); } public async Task CreateAsync(CreateAgenteRequest request, CancellationToken ct = default) { // CPF é validado no domínio (Agente.Create) antes das checagens de unicidade. var agente = Agente.Create(request.Codigo, request.Nome, request.Tipo, request.Cpf, request.Email); await GarantirUnicidadeAsync(agente.Codigo, agente.Cpf, null, ct); await ExecuteInTransactionAsync(() => _repository.AddAsync(agente, ct)); return agente.ToResponse(0); } public async Task UpdateAsync(Guid id, UpdateAgenteRequest request, CancellationToken ct = default) { var agente = await _repository.GetByIdAsync(id, ct) ?? throw new NotFoundException($"Agente {id} não encontrado."); agente.Atualizar(request.Codigo, request.Nome, request.Tipo, request.Cpf, request.Email); await GarantirUnicidadeAsync(agente.Codigo, agente.Cpf, id, ct); await ExecuteInTransactionAsync(() => _repository.UpdateAsync(agente, ct)); var qtd = await _repository.ContarProgramacoesAsync(id, ct); return agente.ToResponse(qtd); } public async Task DeleteAsync(Guid id, CancellationToken ct = default) { var agente = await _repository.GetByIdAsync(id, ct) ?? throw new NotFoundException($"Agente {id} não encontrado."); // Regra do legado: não exclui agente com programação associada. if (await _repository.ContarProgramacoesAsync(id, ct) > 0) throw new ConflictException("Não é possível excluir: o agente possui programação associada."); await ExecuteInTransactionAsync(() => _repository.DeleteAsync(agente.Id, ct)); } private async Task GarantirUnicidadeAsync(string codigo, string? cpf, Guid? excludeId, CancellationToken ct) { if (await _repository.CodigoExistsAsync(codigo, excludeId, ct)) throw new ConflictException($"Já existe um agente com o código '{codigo}'."); if (!string.IsNullOrEmpty(cpf) && await _repository.CpfExistsAsync(cpf, excludeId, ct)) throw new ConflictException("Já existe um agente com esse CPF."); } private async Task ExecuteInTransactionAsync(Func action) { _unitOfWork.BeginTransaction(); try { await action(); _unitOfWork.Commit(); } catch { _unitOfWork.Rollback(); throw; } } }