import Stripe from 'stripe';
import { z } from 'zod';

// Environment variables
const envSchema = z.object({
  STRIPE_SECRET_KEY: z.string().startsWith('sk_'),
  STRIPE_WEBHOOK_SECRET: z.string().startsWith('whsec_'),
  STRIPE_PRICE_ID_BASIC: z.string().startsWith('price_'),
  STRIPE_PRICE_ID_PLUS: z.string().startsWith('price_'),
  STRIPE_PRICE_ID_PREMIUM: z.string().startsWith('price_'),
});

export const billingEnv = envSchema.parse({
  STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY,
  STRIPE_WEBHOOK_SECRET: process.env.STRIPE_WEBHOOK_SECRET,
  STRIPE_PRICE_ID_BASIC: process.env.STRIPE_PRICE_ID_BASIC,
  STRIPE_PRICE_ID_PLUS: process.env.STRIPE_PRICE_ID_PLUS,
  STRIPE_PRICE_ID_PREMIUM: process.env.STRIPE_PRICE_ID_PREMIUM,
});

// Initialize Stripe
export const stripe = new Stripe(billingEnv.STRIPE_SECRET_KEY, {
  apiVersion: '2024-06-20',
  typescript: true,
});

// Subscription tiers
export enum SubscriptionTier {
  BASIC = 'basic',
  PLUS = 'plus',
  PREMIUM = 'premium',
}

// Tier configuration
export const tierConfig: Record<SubscriptionTier, {
  name: string;
  priceId: string;
  features: {
    maxWatchlistItems: number;
    maxFamilyMembers: number;
    darkWebScanFrequency: 'daily' | 'hourly' | 'realtime';
    exposureRetentionMonths: number;
    alertChannels: string[];
  };
}> = {
  [SubscriptionTier.BASIC]: {
    name: 'Basic',
    priceId: billingEnv.STRIPE_PRICE_ID_BASIC,
    features: {
      maxWatchlistItems: 2,
      maxFamilyMembers: 1,
      darkWebScanFrequency: 'daily',
      exposureRetentionMonths: 12,
      alertChannels: ['email'],
    },
  },
  [SubscriptionTier.PLUS]: {
    name: 'Plus',
    priceId: billingEnv.STRIPE_PRICE_ID_PLUS,
    features: {
      maxWatchlistItems: 10,
      maxFamilyMembers: 3,
      darkWebScanFrequency: 'hourly',
      exposureRetentionMonths: 24,
      alertChannels: ['email', 'push'],
    },
  },
  [SubscriptionTier.PREMIUM]: {
    name: 'Premium',
    priceId: billingEnv.STRIPE_PRICE_ID_PREMIUM,
    features: {
      maxWatchlistItems: Infinity,
      maxFamilyMembers: Infinity,
      darkWebScanFrequency: 'realtime',
      exposureRetentionMonths: 60,
      alertChannels: ['email', 'push', 'sms'],
    },
  },
};

// Feature gating middleware
export function getTierFeatures(tier: SubscriptionTier) {
  return tierConfig[tier].features;
}

export function checkFeatureAccess(tier: SubscriptionTier, feature: string, value: number): boolean {
  const features = tierConfig[tier].features;
  const featureValue = features[feature as keyof typeof features] as number;
  return value <= featureValue;
}
