using System.Text.Json; using Microsoft.EntityFrameworkCore; using Tiku.Application.Commerce; using Tiku.Domain.Tenancy; using Tiku.Infrastructure.Persistence; namespace Tiku.Infrastructure.Commerce; internal sealed class TenantSecretService(TikuDbContext dbContext) : ITenantSecretService { public async Task GetActiveSecretPayloadAsync( Guid tenantId, string secretRef, CancellationToken cancellationToken = default) { if (string.IsNullOrWhiteSpace(secretRef)) { throw new PaymentProviderException( "Payment provider secret is not configured.", "payment_secret_not_configured"); } var now = DateTimeOffset.UtcNow; var secret = await dbContext.TenantSecrets .AsNoTracking() .Where(item => item.TenantId == tenantId && item.SecretRef == secretRef && item.Status == TenantSecretStatus.Active && (item.ExpiresAt == null || item.ExpiresAt > now)) .Select(item => item.SecretPayload) .SingleOrDefaultAsync(cancellationToken); if (secret.ValueKind is JsonValueKind.Undefined or JsonValueKind.Null) { throw new PaymentProviderException( "Payment provider secret is not configured.", "payment_secret_not_configured"); } return secret; } }