using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Tiku.Application.PlatformAdmin;
using Tiku.Application.Security;
using Tiku.Domain.Platform;
using Tiku.Infrastructure.Persistence;

namespace Tiku.Infrastructure.PlatformAdmin.TenantProvisioning;

internal sealed class TenantProvisioningReadinessProbe(
    ITenantExecutionScope tenantExecutionScope) : ITenantProvisioningReadinessProbe
{
    public Task<bool> IsPublishedBaseOfferingAvailableAsync(
        string offeringCode,
        CancellationToken cancellationToken = default)
    {
        var normalizedCode = offeringCode.Trim().ToLowerInvariant();
        return tenantExecutionScope.ExecuteAsync(
            new SystemScopeRequest(
                null,
                SystemScopeCallerType.Platform,
                nameof(TenantProvisioningReadinessProbe),
                "Validate the production default tenant offering",
                Guid.NewGuid().ToString("N"),
                true),
            async (services, token) =>
            {
                var persistence = services.GetRequiredService<IPlatformControlPlanePersistence>();
                var now = DateTimeOffset.UtcNow;
                return await (
                    from offering in persistence.SaasOfferings.AsNoTracking()
                    join version in persistence.SaasOfferingVersions.AsNoTracking()
                        on offering.Id equals version.OfferingId
                    where offering.Code == normalizedCode &&
                          offering.Type == SaasOfferingType.BasePlan &&
                          offering.Status == SaasOfferingStatus.Active &&
                          version.Status == SaasOfferingVersionStatus.Published &&
                          (version.EffectiveAt == null || version.EffectiveAt <= now)
                    select version.Id).AnyAsync(token);
            },
            cancellationToken);
    }
}
