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

// --- ASA GENERATED START ---
// Entitlement engine — single source of truth for plan-based access control.
// Entitlements are separated from raw Stripe subscription status.
// Always fetch current state — never trust cached/stale data for access decisions.
// --- ASA GENERATED END ---

// --- USER CODE START ---

export interface EntitlementResult {
  plan: string;
  status: string;
  entitlements: Record<string, boolean | number>;
  can_access: boolean;
}

/**
 * Check what the user is entitled to based on their current subscription.
 * Optionally check a specific feature.
 *
 * Dunning-safe: users in 'past_due' status retain read access
 * but lose write/create capabilities.
 */
export async function checkEntitlement(
  userId: string,
  feature?: string,
): Promise<EntitlementResult> {
  const supabase = createAdminClient();

  // Always fetch current state from DB
  const { data: subscription } = await supabase
    .from('subscriptions')
    .select('plan, status')
    .eq('user_id', userId)
    .single();

  const plan = subscription?.plan ?? 'free';
  const status = subscription?.status ?? 'active';

  // Find plan definition
  const planDef = PLANS.find((p) => p.id === plan);
  const entitlements: Record<string, boolean | number> = {};

  if (planDef?.limits) {
    for (const [key, value] of Object.entries(planDef.limits)) {
      entitlements[key] = value;
    }
  }

  // Dunning-safe access: past_due users keep read access but lose create/write
  const isDunning = status === 'past_due';
  let canAccess = status === 'active' || status === 'trialing' || isDunning;

  if (feature && planDef?.limits) {
    const limit = planDef.limits[feature];
    if (limit === undefined || limit === false || limit === 0) {
      canAccess = false;
    }
    // During dunning, block write-type features
    if (isDunning && feature.startsWith('create_') || isDunning && feature.startsWith('write_')) {
      canAccess = false;
    }
  }

  return { plan, status, entitlements, can_access: canAccess };
}

/**
 * Quick guard: can user access a specific feature?
 */
export async function canAccess(userId: string, feature: string): Promise<boolean> {
  const result = await checkEntitlement(userId, feature);
  return result.can_access;
}

// --- USER CODE END ---
