using CloudServicesCrud;
namespace DynamicCrud.Tests.Grpc;
///
/// Descubre valores reales de la base usando el CRUD dinámico, para alimentar con ellos las
/// pruebas de los servicios legacy. Sin esto habría que hardcodear ids, que cambian entre
/// entornos; y pasar ceros no sirve, porque varios stored procedures interpretan el parámetro
/// nulo como "no coincide con nada" en lugar de "sin filtro".
///
internal sealed class DataProbe
{
private readonly CloudServicesCrud.DynamicCrudService.DynamicCrudServiceClient _client;
private readonly Dictionary<(string, string), string?> _cache = new();
internal DataProbe(CloudServicesCrud.DynamicCrudService.DynamicCrudServiceClient client) =>
_client = client;
///
/// Primer valor no nulo del campo indicado en el modelo. Devuelve null si la tabla está
/// vacía o si todos los registros tienen ese campo en null.
/// El nombre del campo se compara ignorando mayúsculas y guiones bajos, así que sirve
/// tanto "service_id" como "serviceId".
///
internal string? Value(string model, string field)
{
if (_cache.TryGetValue((model, field), out var cached)) return cached;
string? found = null;
var resp = _client.GetAll(new GetAllRequest { Model = model, Limit = 25 });
if (resp.Success)
{
foreach (var record in CrudData.AsRecords(resp.Data))
{
var key = record.Keys.FirstOrDefault(k => Normalize(k) == Normalize(field));
if (key is null) continue;
var value = CrudData.Field(record, key);
if (!string.IsNullOrEmpty(value)) { found = value; break; }
}
}
_cache[(model, field)] = found;
return found;
}
/// Igual que pero convertido a entero; null si no aplica.
internal int? Int(string model, string field) =>
int.TryParse(Value(model, field), out var n) ? n : null;
private static string Normalize(string s) => s.Replace("_", "").ToLowerInvariant();
}