using System.Data; using Dapper; using SCM.Application.Common; using SCM.Domain.Controle; namespace SCM.Infrastructure.Persistence.Repositories; public sealed class ExecutorRepository : IExecutorRepository { private readonly IUnitOfWork _uow; public ExecutorRepository(IUnitOfWork uow) => _uow = uow; private IDbConnection Conn => _uow.Connection; private IDbTransaction? Tx => _uow.CurrentTransaction; private const string Columns = "id, obra_id, codigo, descricao"; public async Task> GetByObraAsync(Guid obraId, CancellationToken ct = default) { const string sql = $"SELECT {Columns} FROM executores WHERE obra_id = @ObraId ORDER BY codigo"; var rows = await Conn.QueryAsync( new CommandDefinition(sql, new { ObraId = obraId }, Tx, cancellationToken: ct)); return rows.ToList(); } public async Task GetByIdAsync(Guid id, CancellationToken ct = default) { const string sql = $"SELECT {Columns} FROM executores WHERE id = @Id"; return await Conn.QueryFirstOrDefaultAsync( new CommandDefinition(sql, new { Id = id }, Tx, cancellationToken: ct)); } public async Task CodigoExistsAsync(string codigo, Guid obraId, Guid? excludeId = null, CancellationToken ct = default) { const string sql = """ SELECT COUNT(*) FROM executores WHERE lower(codigo) = lower(@Codigo) AND obra_id = @ObraId AND (@ExcludeId::uuid IS NULL OR id <> @ExcludeId) """; var count = await Conn.ExecuteScalarAsync(new CommandDefinition( sql, new { Codigo = codigo, ObraId = obraId, ExcludeId = excludeId }, Tx, cancellationToken: ct)); return count > 0; } public async Task ObraExistsAsync(Guid obraId, CancellationToken ct = default) { const string sql = "SELECT COUNT(*) FROM obras WHERE id = @Id"; var count = await Conn.ExecuteScalarAsync( new CommandDefinition(sql, new { Id = obraId }, Tx, cancellationToken: ct)); return count > 0; } public async Task AddAsync(Executor e, CancellationToken ct = default) { const string sql = """ INSERT INTO executores (id, obra_id, codigo, descricao) VALUES (@Id, @ObraId, @Codigo, @Descricao) """; await Conn.ExecuteAsync(new CommandDefinition( sql, new { e.Id, e.ObraId, e.Codigo, e.Descricao }, Tx, cancellationToken: ct)); } public async Task UpdateAsync(Executor e, CancellationToken ct = default) { const string sql = "UPDATE executores SET codigo = @Codigo, descricao = @Descricao WHERE id = @Id"; await Conn.ExecuteAsync(new CommandDefinition( sql, new { e.Id, e.Codigo, e.Descricao }, Tx, cancellationToken: ct)); } public async Task DeleteAsync(Guid id, CancellationToken ct = default) { const string sql = "DELETE FROM executores WHERE id = @Id"; var affected = await Conn.ExecuteAsync( new CommandDefinition(sql, new { Id = id }, Tx, cancellationToken: ct)); return affected > 0; } }