using Microsoft.Extensions.Options;
using Tiku.Application.PlatformAdmin;

namespace Tiku.Api.Configuration;

internal sealed class TenantProvisioningStartupValidator(
    ITenantProvisioningReadinessProbe readinessProbe,
    IOptions<TenantProvisioningOptions> options,
    ILogger<TenantProvisioningStartupValidator> logger) : IHostedService
{
    public async Task StartAsync(CancellationToken cancellationToken)
    {
        var offeringCode = options.Value.DefaultBaseOfferingCode.Trim().ToLowerInvariant();
        var available = await readinessProbe.IsPublishedBaseOfferingAvailableAsync(offeringCode, cancellationToken);

        if (!available)
            throw new InvalidOperationException(
                $"TenantProvisioning:DefaultBaseOfferingCode '{offeringCode}' does not resolve to an effective published base offering version.");

        logger.LogInformation("Validated default tenant provisioning offering {OfferingCode}", offeringCode);
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }
}
