import { createServerClient } from '@/shared/db/supabase-client';

// --- ASA GENERATED START ---
// Entitlement guard API for deterministic feature/limit checks.
// Use these guards in route handlers instead of inline plan checks.
//
// Example:
//   await requireEntitlement(userId, "csv_export");
//   await requireLimit(userId, "max_invoices_per_month", currentCount);
// --- ASA GENERATED END ---

// --- USER CODE START ---

/**
 * Check if user has a boolean entitlement.
 * Throws 403 Response if not entitled.
 */
export async function requireEntitlement(
  userId: string,
  featureKey: string,
): Promise<void> {
  const entitled = await hasEntitlement(userId, featureKey);
  if (!entitled) {
    throw new Response(
      JSON.stringify({
        error: 'FORBIDDEN',
        message: `Entitlement required: ${featureKey}`,
      }),
      { status: 403, headers: { 'Content-Type': 'application/json' } },
    );
  }
}

/**
 * Check if user is within a numeric limit.
 * Throws 403 Response if currentCount >= limit.
 */
export async function requireLimit(
  userId: string,
  limitKey: string,
  currentCount: number,
): Promise<void> {
  const limit = await getLimit(userId, limitKey);
  if (currentCount >= limit) {
    throw new Response(
      JSON.stringify({
        error: 'LIMIT_EXCEEDED',
        message: `Limit exceeded: ${limitKey} (${currentCount}/${limit})`,
      }),
      { status: 403, headers: { 'Content-Type': 'application/json' } },
    );
  }
}

/**
 * Check entitlement without throwing (for conditional UI or soft checks).
 */
export async function hasEntitlement(
  userId: string,
  featureKey: string,
): Promise<boolean> {
  const supabase = createServerClient();
  const { data } = await supabase
    .from('entitlements')
    .select('value')
    .eq('user_id', userId)
    .eq('feature_key', featureKey)
    .single();

  return data?.value === 'true';
}

/**
 * Get numeric limit value for a user. Returns 0 if not found.
 */
export async function getLimit(
  userId: string,
  limitKey: string,
): Promise<number> {
  const supabase = createServerClient();
  const { data } = await supabase
    .from('entitlements')
    .select('value')
    .eq('user_id', userId)
    .eq('feature_key', limitKey)
    .single();

  return data ? parseInt(data.value, 10) : 0;
}

/**
 * Get all entitlements for a user (for UI display or bulk checks).
 */
export async function getEntitlements(
  userId: string,
): Promise<Map<string, string>> {
  const supabase = createServerClient();
  const { data } = await supabase
    .from('entitlements')
    .select('feature_key, value')
    .eq('user_id', userId);

  const map = new Map<string, string>();
  (data ?? []).forEach((row: { feature_key: string; value: string }) =>
    map.set(row.feature_key, row.value),
  );
  return map;
}

// --- USER CODE END ---
