using System.Text.Json;
using System.Text.Json.Serialization;
using JdeScoping.Core.Models.Enums;
using Microsoft.Extensions.Logging;
namespace JdeScoping.Core.Models.Search;
///
/// User search request entity
///
public class Search
{
///
/// PK ID of search
///
public int Id { get; set; }
///
/// User name of user that created search
///
public string UserName { get; set; } = string.Empty;
///
/// User-friendly name for search
///
public string Name { get; set; } = string.Empty;
///
/// Current search status
///
[JsonConverter(typeof(JsonStringEnumConverter))]
public SearchStatus Status { get; set; }
///
/// Timestamp search was submitted
///
public DateTime? SubmitDt { get; set; }
///
/// Timestamp search was started
///
public DateTime? StartDt { get; set; }
///
/// Timestamp search was completed
///
public DateTime? EndDt { get; set; }
///
/// JSON-packed search criteria (stored in database)
///
public string CriteriaJson { get; set; } = string.Empty;
///
/// Search criteria (deserialized from CriteriaJSON)
///
[JsonIgnore]
public SearchCriteria? Criteria
{
get
{
TryGetCriteria(out var criteria);
return criteria;
}
set
{
CriteriaJson = value != null
? JsonSerializer.Serialize(value)
: string.Empty;
}
}
///
/// Attempts to deserialize the search criteria from JSON.
///
/// The deserialized criteria, or null if deserialization fails or JSON is empty.
/// Optional logger for warning on deserialization failures.
/// True if deserialization succeeded or JSON was empty; false if deserialization failed.
public bool TryGetCriteria(out SearchCriteria? criteria, ILogger? logger = null)
{
criteria = null;
if (string.IsNullOrEmpty(CriteriaJson))
return true; // Empty is valid, not an error
try
{
criteria = JsonSerializer.Deserialize(CriteriaJson);
return true;
}
catch (JsonException ex)
{
logger?.LogWarning(ex, "Failed to deserialize search criteria for Search ID {SearchId}", Id);
return false;
}
}
///
/// Excel search results file (binary)
///
public byte[]? Results { get; set; }
}