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

namespace Tiku.Infrastructure.QuestionBanks;

public sealed class PublicQuestionAccessPolicy(
    TikuDbContext dbContext,
    IFeatureAccessService featureAccessService) : 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 subscriptionIsActive = (await featureAccessService.EvaluateAsync(
            tenantId,
            SaasFeatureCatalog.Practice,
            FeatureAccessOperation.Write,
            cancellationToken)).Allowed;

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