/**
 * Vigthoria Coder subscription plan gating.
 *
 * Mirrors the exact same plan sets/normalization used server-side in
 * vigthoria-coder/server.js (CODER_PLANS) and vigthoria-user-hub/lib/
 * agent-voice-access.js, so the Workbench's client-side gating stays in
 * sync with the authoritative server-side checks. This is a UX gate (clear
 * "upgrade required" messaging) -- the real enforcement lives server-side
 * in vigthoria-template-service and vigthoria-hyper-loop, which both
 * live-verify against Coder's /api/user/subscription and fail closed.
 */
import type { VigthoriaAuthStatus } from '@/types/workbench';

/** Any active Vigthoria Coder subscription -- required for Templates. */
export const CODER_PLANS = new Set([
  'developer',
  'professional',
  'pro',
  'enterprise',
  'master_admin',
  'master-admin-plan',
]);

/**
 * Higher-tier plans only -- required for Hyper-Loop and GOA. Deliberately
 * excludes bare "developer".
 */
export const HYPER_TIER_PLANS = new Set([
  'pro',
  'professional',
  'enterprise',
  'master_admin',
  'master-admin-plan',
]);

export function normalizePlanId(plan?: string | null): string {
  return String(plan || '').trim().toLowerCase().replace(/-/g, '_');
}

function isAdminAuth(auth: VigthoriaAuthStatus): boolean {
  return !!(auth.isAdmin || auth.isMasterAdmin);
}

/** Does this auth state have ANY active Coder plan (or admin)? Gates Templates. */
export function hasAnyCoderPlan(auth: VigthoriaAuthStatus): boolean {
  if (!auth.authenticated) return false;
  if (isAdminAuth(auth)) return true;
  const normalized = normalizePlanId(auth.plan);
  return CODER_PLANS.has(normalized) || CODER_PLANS.has(String(auth.plan || '').trim().toLowerCase());
}

/** Does this auth state have a HIGHER-tier plan (or admin)? Gates Hyper-Loop/GOA. */
export function hasHyperTierPlan(auth: VigthoriaAuthStatus): boolean {
  if (!auth.authenticated) return false;
  if (isAdminAuth(auth)) return true;
  const normalized = normalizePlanId(auth.plan);
  return HYPER_TIER_PLANS.has(normalized) || HYPER_TIER_PLANS.has(String(auth.plan || '').trim().toLowerCase());
}

export const CODER_UPGRADE_URL = 'https://landing.vigthoria.io/pricing.html#coder';
