/**
 * Feature Flags System for Mawidi Platform
 * ==========================================
 * Environment-based feature toggles for safe rollouts
 *
 * IMPORTANT:
 * - All risky features default to OFF
 * - Enable flags via environment variables
 * - Use flags to gate risky or experimental features
 *
 * Usage:
 *   import { flags, isFeatureEnabled } from '@/lib/feature-flags';
 *
 *   if (flags.STRIPE_WEBHOOK_V2) {
 *     // New webhook handling
 *   } else {
 *     // Old webhook handling
 *   }
 *
 * Environment Variables:
 *   FEATURE_STRIPE_V2=true|false
 *   FEATURE_NEW_AUTH=true|false
 *   FEATURE_BILLING_V2=true|false
 *   FEATURE_ANALYTICS_V2=true|false
 *   FEATURE_DASHBOARD_REDESIGN=true|false
 */

/**
 * Feature flag definitions with descriptions and risk levels
 */
export interface FeatureFlag {
  name: string;
  description: string;
  riskLevel: "low" | "medium" | "high" | "critical";
  defaultValue: boolean;
  envVar: string;
}

export const FEATURE_DEFINITIONS: Record<string, FeatureFlag> = {
  STRIPE_WEBHOOK_V2: {
    name: "Stripe Webhook V2",
    description: "New Stripe webhook processing with improved error handling",
    riskLevel: "critical",
    defaultValue: false,
    envVar: "FEATURE_STRIPE_V2",
  },
  NEW_AUTH_FLOW: {
    name: "New Authentication Flow",
    description: "Redesigned authentication with improved security",
    riskLevel: "critical",
    defaultValue: false,
    envVar: "FEATURE_NEW_AUTH",
  },
  BILLING_V2: {
    name: "Billing System V2",
    description: "New billing system with multi-currency support",
    riskLevel: "high",
    defaultValue: false,
    envVar: "FEATURE_BILLING_V2",
  },
  ANALYTICS_V2: {
    name: "Analytics Dashboard V2",
    description: "Enhanced analytics with real-time metrics",
    riskLevel: "medium",
    defaultValue: false,
    envVar: "FEATURE_ANALYTICS_V2",
  },
  DASHBOARD_REDESIGN: {
    name: "Dashboard Redesign",
    description: "New dashboard UI with improved UX",
    riskLevel: "medium",
    defaultValue: false,
    envVar: "FEATURE_DASHBOARD_REDESIGN",
  },
  ENHANCED_NOTIFICATIONS: {
    name: "Enhanced Notifications",
    description: "Real-time notification system improvements",
    riskLevel: "low",
    defaultValue: false,
    envVar: "FEATURE_ENHANCED_NOTIFICATIONS",
  },
  ONBOARDING_V2: {
    name: "Onboarding Flow V2",
    description: "Improved onboarding wizard with better guidance",
    riskLevel: "low",
    defaultValue: false,
    envVar: "FEATURE_ONBOARDING_V2",
  },
  WHATSAPP_BETA: {
    name: "WhatsApp Beta Features",
    description: "Beta WhatsApp integration features",
    riskLevel: "medium",
    defaultValue: false,
    envVar: "FEATURE_WHATSAPP_BETA",
  },
} as const;

/**
 * Parse boolean from environment variable
 */
function parseBoolean(
  value: string | undefined,
  defaultValue: boolean,
): boolean {
  if (value === undefined || value === "") return defaultValue;
  return value.toLowerCase() === "true" || value === "1";
}

/**
 * Active feature flags based on environment variables
 * All flags default to OFF for safety
 */
export const flags = {
  // Critical - Payments and Auth
  STRIPE_WEBHOOK_V2: parseBoolean(process.env.FEATURE_STRIPE_V2, false),
  NEW_AUTH_FLOW: parseBoolean(process.env.FEATURE_NEW_AUTH, false),

  // High Risk - Billing
  BILLING_V2: parseBoolean(process.env.FEATURE_BILLING_V2, false),

  // Medium Risk - UI/UX
  ANALYTICS_V2: parseBoolean(process.env.FEATURE_ANALYTICS_V2, false),
  DASHBOARD_REDESIGN: parseBoolean(
    process.env.FEATURE_DASHBOARD_REDESIGN,
    false,
  ),
  WHATSAPP_BETA: parseBoolean(process.env.FEATURE_WHATSAPP_BETA, false),

  // Low Risk - Enhancements
  ENHANCED_NOTIFICATIONS: parseBoolean(
    process.env.FEATURE_ENHANCED_NOTIFICATIONS,
    false,
  ),
  ONBOARDING_V2: parseBoolean(process.env.FEATURE_ONBOARDING_V2, false),

  // Development flags
  DEBUG_MODE: parseBoolean(
    process.env.FEATURE_DEBUG_MODE,
    process.env.NODE_ENV === "development",
  ),
  VERBOSE_LOGGING: parseBoolean(process.env.FEATURE_VERBOSE_LOGGING, false),
} as const;

/**
 * Type-safe flag names
 */
export type FeatureFlagName = keyof typeof flags;

/**
 * Check if a specific feature is enabled
 */
export function isFeatureEnabled(flagName: FeatureFlagName): boolean {
  return flags[flagName] ?? false;
}

/**
 * Get all enabled features
 */
export function getEnabledFeatures(): FeatureFlagName[] {
  return (Object.keys(flags) as FeatureFlagName[]).filter((key) => flags[key]);
}

/**
 * Get all disabled features
 */
export function getDisabledFeatures(): FeatureFlagName[] {
  return (Object.keys(flags) as FeatureFlagName[]).filter((key) => !flags[key]);
}

/**
 * Get features by risk level
 */
export function getFeaturesByRiskLevel(
  riskLevel: "low" | "medium" | "high" | "critical",
): string[] {
  return Object.entries(FEATURE_DEFINITIONS)
    .filter(([, def]) => def.riskLevel === riskLevel)
    .map(([key]) => key);
}

/**
 * Get enabled high-risk features (for release checks)
 */
export function getEnabledHighRiskFeatures(): string[] {
  const highRiskLevels = ["high", "critical"];
  return Object.entries(FEATURE_DEFINITIONS)
    .filter(
      ([key, def]) =>
        highRiskLevels.includes(def.riskLevel) && flags[key as FeatureFlagName],
    )
    .map(([key]) => key);
}

/**
 * Feature flag status for debugging/monitoring
 */
export function getFeatureFlagStatus() {
  return {
    enabled: getEnabledFeatures(),
    disabled: getDisabledFeatures(),
    highRiskEnabled: getEnabledHighRiskFeatures(),
    timestamp: new Date().toISOString(),
    environment: process.env.NODE_ENV,
  };
}

/**
 * Log feature flag status (useful for debugging)
 */
export function logFeatureFlags(): void {
  const status = getFeatureFlagStatus();
  console.log("[Feature Flags]", JSON.stringify(status, null, 2));
}

/**
 * React hook-compatible feature check
 * Note: For client-side use, flags are evaluated at build time
 */
export function useFeatureFlag(flagName: FeatureFlagName): boolean {
  return isFeatureEnabled(flagName);
}

/**
 * Conditional component wrapper
 * Usage: <FeatureGate flag="DASHBOARD_REDESIGN"><NewDashboard /></FeatureGate>
 */
export function shouldRenderFeature(flagName: FeatureFlagName): boolean {
  return isFeatureEnabled(flagName);
}

// Export default for convenience
export default flags;
