File size: 3,566 Bytes
de8b914
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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<IReadOnlyList<AgenteResponse>> GetAllAsync(CancellationToken ct = default)
    {
        var itens = await _repository.GetAllAsync(ct);
        return itens.Select(x => x.Agente.ToResponse(x.QtdProgramacoes)).ToList();
    }

    public async Task<AgenteResponse> 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<AgenteResponse> 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<AgenteResponse> 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<Task> action)
    {
        _unitOfWork.BeginTransaction();
        try
        {
            await action();
            _unitOfWork.Commit();
        }
        catch
        {
            _unitOfWork.Rollback();
            throw;
        }
    }
}