/**
 * TabataFit RevenueCat Service
 * Initialize and configure RevenueCat for Apple subscriptions
 *
 * Sandbox testing:
 * - The test_ API key enables RevenueCat sandbox mode
 * - StoreKit Configuration (TabataFit.storekit) enables simulator purchases
 * - Transactions are free sandbox completions — no real charges
 */

import { logger } from '../utils/logger'
import Purchases, { LOG_LEVEL } from 'react-native-purchases'

// RevenueCat configuration
// test_ prefix = sandbox mode (free transactions on simulator + device sandbox accounts)
// Set EXPO_PUBLIC_REVENUECAT_API_KEY in .env for production
export const REVENUECAT_API_KEY =
  process.env.EXPO_PUBLIC_REVENUECAT_API_KEY || 'test_oIJbIHWISJaUZdgxRMHlwizBHvM'

// Entitlement ID configured in RevenueCat dashboard
export const ENTITLEMENT_ID = '1000 Corp Pro'

// Track initialization state
let isInitialized = false

/**
 * Initialize RevenueCat SDK
 * Call this once at app startup (after store hydration)
 */
export async function initializePurchases(): Promise<void> {
  if (isInitialized) {
    logger.log('[Purchases] Already initialized')
    return
  }

  try {
    // setLogLevel MUST be called before configure()
    if (__DEV__) {
      Purchases.setLogLevel(LOG_LEVEL.VERBOSE)
    }

    // Configure RevenueCat with API key
    await Purchases.configure({ apiKey: REVENUECAT_API_KEY })

    isInitialized = true
    logger.log('[Purchases] RevenueCat initialized successfully')
    logger.log('[Purchases] Sandbox mode:', __DEV__ ? 'enabled' : 'disabled')
  } catch (error) {
    logger.error('[Purchases] Failed to initialize RevenueCat:', error)
    throw error
  }
}

/**
 * Check if RevenueCat has been initialized
 */
export function isPurchasesInitialized(): boolean {
  return isInitialized
}
