using System.Text.Json;
using Microsoft.Extensions.Logging;
namespace Registration.Data;
///
/// Real data service backed by dbRegistration.
/// Calls dbo.spRegistration with the standard @action/@rqst/@resp pattern.
///
/// Activate by swapping DI registration in Program.cs:
/// services.AddSingleton<IRegistrationDataService, SqlDataService>();
///
public class SqlDataService : IRegistrationDataService
{
private readonly SqlService _sql;
private readonly ILogger _log;
private const string Proc = "dbo.spRegistration";
public SqlDataService(SqlService sql, ILogger log)
{
_sql = sql;
_log = log;
}
public async Task GetPendingAsync(CancellationToken ct)
{
var resp = await _sql.ExecProcAsync(Proc, "pending", "{}", ct: ct);
return JsonSerializer.Deserialize(resp, JsonOpts)
?? new() { Ok = false };
}
public async Task GetByIdAsync(string registrationId, CancellationToken ct)
{
var rqst = JsonSerializer.Serialize(new { registrationId });
var resp = await _sql.ExecProcAsync(Proc, "get", rqst, ct: ct);
using var doc = JsonDocument.Parse(resp);
if (doc.RootElement.TryGetProperty("applicant", out var app))
return JsonSerializer.Deserialize(app.GetRawText(), JsonOpts);
return null;
}
public async Task RegisterAsync(RegisterRequest request, CancellationToken ct)
{
var rqst = JsonSerializer.Serialize(request, JsonOpts);
var resp = await _sql.ExecProcAsync(Proc, "register", rqst, ct: ct);
return JsonSerializer.Deserialize(resp, JsonOpts)
?? new() { Ok = false, Error = "Deserialization failed" };
}
public async Task RejectAsync(string registrationId, string? reason, string? rejectedBy, CancellationToken ct)
{
var rqst = JsonSerializer.Serialize(new { registrationId, reason, rejectedBy });
var resp = await _sql.ExecProcAsync(Proc, "reject", rqst, ct: ct);
return JsonSerializer.Deserialize(resp, JsonOpts)
?? new() { Ok = false, Error = "Deserialization failed" };
}
public async Task CompleteAsync(string registrationId, string? platformClientId, CancellationToken ct)
{
var rqst = JsonSerializer.Serialize(new { registrationId, platformClientId });
var resp = await _sql.ExecProcAsync(Proc, "complete", rqst, ct: ct);
return JsonSerializer.Deserialize(resp, JsonOpts)
?? new() { Ok = false, Error = "Deserialization failed" };
}
private static readonly JsonSerializerOptions JsonOpts = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true
};
}