/**
 * Central access check for every kids AI endpoint:
 *  - active session
 *  - parent has enabled AI + this specific feature
 *  - per-day usage cap not exceeded
 *  - short-term rate limit
 * Server-only.
 */
import { getActiveSubscriberId } from '../session';
import { aiFeatureEnabled, getAiSettings, getAiUsageToday, incrementAiUsage } from '../repo';
import { rateLimit } from '../ratelimit';

export interface GateOk {
  ok: true;
  subscriberId: string;
}
export interface GateFail {
  ok: false;
  status: number;
  error: string;
}

export function checkAiAccess(feature: string): GateOk | GateFail {
  const subscriberId = getActiveSubscriberId();
  if (!subscriberId) return { ok: false, status: 401, error: 'সেশন নেই।' };

  const ai = getAiSettings(subscriberId);
  if (!ai.enabled) {
    return { ok: false, status: 403, error: 'AI বন্ধ আছে। Parent Zone থেকে চালু করো।' };
  }
  if (!aiFeatureEnabled(subscriberId, feature)) {
    return { ok: false, status: 403, error: 'এই AI ফিচারটা এখন বন্ধ আছে।' };
  }
  if (getAiUsageToday(subscriberId) >= ai.dailyLimit) {
    return { ok: false, status: 429, error: 'আজকের AI সময় শেষ। কাল আবার এসো! 🌙' };
  }
  const rl = rateLimit(`ai:${subscriberId}`, 5, 0.2); // burst 5, ~1 per 5s
  if (!rl.ok) {
    return { ok: false, status: 429, error: 'একটু ধীরে! আরেকটু পরে চেষ্টা করো। 😊' };
  }
  return { ok: true, subscriberId };
}

export function recordAiUse(subscriberId: string, feature: string) {
  incrementAiUsage(subscriberId, feature);
}
