using Dapper; using SIGCM.Domain.Entities; using SIGCM.Infrastructure.Data; namespace SIGCM.Infrastructure.Repositories; public class ClientRepository { private readonly IDbConnectionFactory _db; public ClientRepository(IDbConnectionFactory db) { _db = db; } // Búsqueda inteligente por Nombre O DNI public async Task> SearchAsync(string query) { using var conn = _db.CreateConnection(); var sql = @" SELECT TOP 10 * FROM Clients WHERE Name LIKE @Query OR DniOrCuit LIKE @Query ORDER BY Name"; return await conn.QueryAsync(sql, new { Query = $"%{query}%" }); } // Buscar o Crear (Upsert) al guardar el aviso public async Task EnsureClientExistsAsync(string name, string dni) { using var conn = _db.CreateConnection(); // 1. Buscamos por DNI/CUIT (es el identificador único más fiable) var existingId = await conn.ExecuteScalarAsync( "SELECT Id FROM Clients WHERE DniOrCuit = @Dni", new { Dni = dni }); if (existingId.HasValue) { // Opcional: Actualizar nombre si cambió await conn.ExecuteAsync("UPDATE Clients SET Name = @Name WHERE Id = @Id", new { Name = name, Id = existingId }); return existingId.Value; } else { // Crear nuevo var sql = @" INSERT INTO Clients (Name, DniOrCuit) VALUES (@Name, @Dni); SELECT CAST(SCOPE_IDENTITY() as int);"; return await conn.QuerySingleAsync(sql, new { Name = name, Dni = dni }); } } public async Task> GetAllWithStatsAsync() { using var conn = _db.CreateConnection(); var sql = @" SELECT c.*, (SELECT COUNT(1) FROM Listings l WHERE l.ClientId = c.Id) as TotalAds, (SELECT SUM(AdFee) FROM Listings l WHERE l.ClientId = c.Id) as TotalSpent FROM Clients c ORDER BY c.Name"; return await conn.QueryAsync(sql); } public async Task> GetClientHistoryAsync(int clientId) { using var conn = _db.CreateConnection(); return await conn.QueryAsync( "SELECT * FROM Listings WHERE ClientId = @Id ORDER BY CreatedAt DESC", new { Id = clientId }); } }