import { z } from 'zod';

// Environment variables for analytics
const envSchema = z.object({
  MIXPANEL_TOKEN: z.string(),
  MIXPANEL_API_SECRET: z.string().optional(),
  GA4_MEASUREMENT_ID: z.string(),
  GA4_API_SECRET: z.string().optional(),
  STRIPE_WEBHOOK_SECRET: z.string(),
  ANALYTICS_ENV: z.enum(['development', 'production', 'staging']).default('development'),
});

export const analyticsEnv = envSchema.parse({
  MIXPANEL_TOKEN: process.env.MIXPANEL_TOKEN,
  MIXPANEL_API_SECRET: process.env.MIXPANEL_API_SECRET,
  GA4_MEASUREMENT_ID: process.env.GA4_MEASUREMENT_ID,
  GA4_API_SECRET: process.env.GA4_API_SECRET,
  STRIPE_WEBHOOK_SECRET: process.env.STRIPE_WEBHOOK_SECRET,
  ANALYTICS_ENV: process.env.ANALYTICS_ENV,
});

// Event taxonomy
export enum EventType {
  // User events
  USER_SIGNED_UP = 'user_signed_up',
  USER_LOGGED_IN = 'user_logged_in',
  USER_LOGGED_OUT = 'user_logged_out',
  USER_UPGRADED = 'user_upgraded',
  USER_DOWNGRADED = 'user_downgraded',
  
  // Subscription events
  SUBSCRIPTION_CREATED = 'subscription_created',
  SUBSCRIPTION_UPDATED = 'subscription_updated',
  SUBSCRIPTION_CANCELLED = 'subscription_cancelled',
  SUBSCRIPTION_RENEWED = 'subscription_renewed',
  
  // DarkWatch events
  DARK_WEB_SCAN_STARTED = 'dark_web_scan_started',
  DARK_WEB_SCAN_COMPLETED = 'dark_web_scan_completed',
  EXPOSURE_DETECTED = 'exposure_detected',
  EXPOSURE_RESOLVED = 'exposure_resolved',
  WATCHLIST_ITEM_ADDED = 'watchlist_item_added',
  WATCHLIST_ITEM_REMOVED = 'watchlist_item_removed',
  
  // VoicePrint events
  VOICE_ENROLLED = 'voice_enrolled',
  VOICE_ANALYZED = 'voice_analyzed',
  VOICE_MATCH_FOUND = 'voice_match_found',
  SYNTHETIC_VOICE_DETECTED = 'synthetic_voice_detected',
  
  // SpamShield events
  CALL_ANALYZED = 'call_analyzed',
  SMS_ANALYZED = 'sms_analyzed',
  SPAM_BLOCKED = 'spam_blocked',
  SPAM_FLAGGED = 'spam_flagged',
  SPAM_FEEDBACK_SUBMITTED = 'spam_feedback_submitted',
  
  // KPI events
  MRR_UPDATED = 'mrr_updated',
  CONVERSION_OCCURRED = 'conversion_occurred',
  CHURN_OCCURRED = 'churn_occurred',
  REFERRAL_SENT = 'referral_sent',
  REFERRAL_CONVERTED = 'referral_converted',
}

// Event properties schema
export const eventPropertiesSchema = z.object({
  userId: z.string().optional(),
  sessionId: z.string().optional(),
  timestamp: z.date().optional(),
  platform: z.enum(['web', 'mobile', 'desktop', 'api']).optional(),
  version: z.string().optional(),
  environment: z.string().optional(),
});

// KPI definitions
export const kpiDefinitions = {
  mau: {
    name: 'Monthly Active Users',
    description: 'Unique users who performed an action in the last 30 days',
    calculation: 'COUNT(DISTINCT userId) WHERE timestamp > NOW() - INTERVAL 30 DAYS',
  },
  payingUsers: {
    name: 'Paying Users',
    description: 'Users with active subscriptions',
    calculation: 'COUNT(DISTINCT userId) WHERE subscription.status = "active"',
  },
  mrr: {
    name: 'Monthly Recurring Revenue',
    description: 'Total monthly subscription revenue',
    calculation: 'SUM(subscription.amount) WHERE subscription.status = "active"',
  },
  conversionRate: {
    name: 'Conversion Rate',
    description: 'Percentage of free users who upgrade to paid',
    calculation: 'COUNT(upgrade events) / COUNT(signup events)',
  },
  churn: {
    name: 'Churn Rate',
    description: 'Percentage of paying users who cancel',
    calculation: 'COUNT(cancel events) / COUNT(active subscriptions)',
  },
  cac: {
    name: 'Customer Acquisition Cost',
    description: 'Average cost to acquire a new paying user',
    calculation: 'Total marketing spend / COUNT(new paying users)',
  },
  ltv: {
    name: 'Lifetime Value',
    description: 'Average revenue per user over their lifetime',
    calculation: 'Average subscription amount / Churn rate',
  },
  nps: {
    name: 'Net Promoter Score',
    description: 'Customer satisfaction metric (-100 to 100)',
    calculation: '% Promoters - % Detractors',
  },
  viralCoefficient: {
    name: 'Viral Coefficient',
    description: 'Average number of referrals per user',
    calculation: 'COUNT(referral events) / COUNT(users)',
  },
};

// Alert thresholds
export const alertThresholds = {
  churn: { warning: 0.05, critical: 0.10 },
  conversionRate: { warning: 0.02, critical: 0.01 },
  mrr: { warning: 0.90, critical: 0.80 }, // Percentage of target
  nps: { warning: 50, critical: 40 },
  viralCoefficient: { warning: 0.4, critical: 0.3 },
};
