using Microsoft.EntityFrameworkCore;
using Tiku.Application.QuestionBanks;
using Tiku.Domain.Commerce;
using Tiku.Domain.Tenancy;
using Tiku.Infrastructure.Persistence;

namespace Tiku.Infrastructure.QuestionBanks;

public sealed class PublicQuestionAccessPolicy(TikuDbContext dbContext) : IPublicQuestionAccessPolicy
{
    public async Task EnsureCanStartAsync(Guid tenantId, CancellationToken cancellationToken = default)
    {
        var tenantIsActive = await dbContext.Tenants.AsNoTracking().AnyAsync(
            tenant => tenant.Id == tenantId && tenant.Status == TenantStatus.Active,
            cancellationToken);
        var now = DateTimeOffset.UtcNow;
        var subscriptionIsActive = await dbContext.TenantSubscriptions.AsNoTracking().AnyAsync(
            subscription =>
                subscription.TenantId == tenantId &&
                (subscription.Status == TenantSubscriptionStatus.Trial ||
                 subscription.Status == TenantSubscriptionStatus.Active) &&
                (!subscription.StartsAt.HasValue || subscription.StartsAt <= now) &&
                (!subscription.ExpiresAt.HasValue || subscription.ExpiresAt > now),
            cancellationToken);

        if (!tenantIsActive || !subscriptionIsActive)
        {
            throw new PublicQuestionAccessDeniedException(
                "public_question_subscription_required",
                "An active trial or subscription is required to start public question practice.");
        }
    }
}
