#nullable enable
using System.Text;
using Baya.Application.Contracts.Common;
using Microsoft.Extensions.Diagnostics.HealthChecks;

namespace Baya.Infrastructure.Monitoring.HealthChecks;

/// <summary>
/// Readiness probe for the <see cref="IObjectStorage"/> seam (verification documents, avatars, invoice PDFs):
/// a deploy can pass a DB-only health check while uploads are broken. This does a real round-trip —
/// write a tiny probe blob, read it back, delete it — so a misconfigured bucket / unreachable endpoint /
/// missing write permission surfaces as <see cref="HealthStatus.Unhealthy"/> rather than a first-user 500.
/// The probe key is namespaced and deleted every run, so it never accumulates.
/// </summary>
internal sealed class ObjectStorageWriteHealthCheck(IObjectStorage objectStorage) : IHealthCheck
{
    private const string ProbeKey = "healthz/object-storage-probe";
    private static readonly byte[] ProbePayload = Encoding.UTF8.GetBytes("ok");

    public async Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context,
        CancellationToken cancellationToken = default)
    {
        try
        {
            await using (var writeStream = new MemoryStream(ProbePayload, writable: false))
                await objectStorage.PutAsync(ProbeKey, writeStream, "text/plain", cancellationToken);

            await using var readStream = await objectStorage.GetAsync(ProbeKey, cancellationToken);
            if (readStream is null)
                return HealthCheckResult.Unhealthy("Object storage write succeeded but the probe blob was not readable.");

            await objectStorage.DeleteAsync(ProbeKey, cancellationToken);
            return HealthCheckResult.Healthy();
        }
        catch (Exception ex)
        {
            return HealthCheckResult.Unhealthy("Object storage round-trip failed.", ex);
        }
    }
}
