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

// --- ASA GENERATED START ---
// Entitlement resolver — syncs entitlements from plan_features when subscription changes.
// Called from Stripe webhook handler on plan change events.
// --- ASA GENERATED END ---

// --- USER CODE START ---

/**
 * Sync entitlements for user based on their current plan.
 *
 * Flow:
 * 1. Read plan_features for planKey
 * 2. Delete old plan-sourced entitlements (keep overrides)
 * 3. Insert new entitlements from plan
 *
 * Called from:
 * - Stripe webhook handler (plan change)
 * - User registration (set free plan defaults)
 */
export async function syncEntitlements(
  userId: string,
  planKey: string,
): Promise<void> {
  const supabase = createAdminClient();

  // 1. Get plan features
  const { data: planFeatures } = await supabase
    .from('plan_features')
    .select('*')
    .eq('plan_key', planKey);

  if (!planFeatures || planFeatures.length === 0) {
    console.warn(`[ASA Entitlements] No plan_features found for plan: ${planKey}`);
    return;
  }

  // 2. Delete old plan-sourced entitlements (keep overrides)
  await supabase
    .from('entitlements')
    .delete()
    .eq('user_id', userId)
    .eq('source', 'plan');

  // 3. Insert new entitlements from plan
  const rows = planFeatures.map((pf: { feature_key: string; feature_type: string; value: string }) => ({
    user_id: userId,
    feature_key: pf.feature_key,
    feature_type: pf.feature_type,
    value: pf.value,
    source: 'plan',
  }));

  const { error } = await supabase.from('entitlements').insert(rows);
  if (error) {
    console.error(`[ASA Entitlements] Failed to sync entitlements for user ${userId}:`, error);
  }
}

// --- USER CODE END ---
