/**
 * WhatsApp Feature Access Service
 *
 * Checks whether an organization has access to WhatsApp features
 * based on their subscription tier.
 */

import { prisma } from '@/lib/db';
import { logger } from '@/lib/logger';

/**
 * Require that the organization has WhatsApp feature access.
 * Throws an error if not authorized.
 */
export async function requireFeatureAccess(organizationId: string): Promise<void> {
  try {
    const org = await prisma.organizations.findUnique({
      where: { id: organizationId },
      select: { id: true, ownerId: true },
    });

    if (!org) {
      throw new Error('Organization not found');
    }

    // Check subscription tier allows WhatsApp
    const subscription = await prisma.subscriptions.findFirst({
      where: {
        userId: org.ownerId,
        status: 'active',
      },
      select: { tierId: true },
    });

    // For now, allow all tiers that have an active subscription
    if (!subscription) {
      throw new Error('Active subscription required for WhatsApp features');
    }
  } catch (error) {
    if (error instanceof Error && (error.message.includes('not found') || error.message.includes('required'))) {
      throw error;
    }
    logger.warn('[whatsapp-feature-access] Check failed, allowing access', { organizationId });
    // Gracefully allow if table doesn't exist yet
  }
}
