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

namespace Tiku.Api.Configuration;

internal sealed class TenantProvisioningStartupValidator(
    ITenantExecutionScope tenantExecutionScope,
    IOptions<TenantProvisioningOptions> options,
    ILogger<TenantProvisioningStartupValidator> logger) : IHostedService
{
    public async Task StartAsync(CancellationToken cancellationToken)
    {
        var offeringCode = options.Value.DefaultBaseOfferingCode.Trim().ToLowerInvariant();
        var available = await tenantExecutionScope.ExecuteAsync(
            new SystemScopeRequest(
                null,
                SystemScopeCallerType.Platform,
                nameof(TenantProvisioningStartupValidator),
                "Validate the production default tenant offering",
                Guid.NewGuid().ToString("N"),
                true),
            async (services, token) =>
            {
                var dbContext = services.GetRequiredService<TikuDbContext>();
                var now = DateTimeOffset.UtcNow;
                return await (
                    from offering in dbContext.SaasOfferings.AsNoTracking()
                    join version in dbContext.SaasOfferingVersions.AsNoTracking()
                        on offering.Id equals version.OfferingId
                    where offering.Code == offeringCode &&
                          offering.Type == SaasOfferingType.BasePlan &&
                          offering.Status == SaasOfferingStatus.Active &&
                          version.Status == SaasOfferingVersionStatus.Published &&
                          (version.EffectiveAt == null || version.EffectiveAt <= now)
                    select version.Id).AnyAsync(token);
            },
            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;
    }
}