import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import Purchases, { LOG_LEVEL } from 'react-native-purchases'

vi.mock('react-native-purchases', () => ({
  default: {
    configure: vi.fn(),
    setLogLevel: vi.fn(),
  },
  LOG_LEVEL: {
    VERBOSE: 'VERBOSE',
    DEBUG: 'DEBUG',
    WARN: 'WARN',
    ERROR: 'ERROR',
  },
}))

describe('purchases service', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    vi.resetModules()
  })

  afterEach(() => {
    vi.restoreAllMocks()
  })

  describe('constants', () => {
    it('should export REVENUECAT_API_KEY', async () => {
      const { REVENUECAT_API_KEY } = await import('../../shared/services/purchases')
      expect(REVENUECAT_API_KEY).toBeDefined()
      expect(REVENUECAT_API_KEY).toContain('test_')
    })

    it('should export ENTITLEMENT_ID', async () => {
      const { ENTITLEMENT_ID } = await import('../../shared/services/purchases')
      expect(ENTITLEMENT_ID).toBeDefined()
      expect(ENTITLEMENT_ID).toBe('1000 Corp Pro')
    })
  })

  describe('initializePurchases', () => {
    it('should call configure with API key', async () => {
      const { initializePurchases } = await import('../../shared/services/purchases')
      
      await initializePurchases()
      
      expect(Purchases.configure).toHaveBeenCalled()
    })

    it('should set log level in dev mode', async () => {
      const { initializePurchases } = await import('../../shared/services/purchases')
      
      await initializePurchases()
      
      if (__DEV__) {
        expect(Purchases.setLogLevel).toHaveBeenCalledWith(LOG_LEVEL.VERBOSE)
      }
    })

    it('should only initialize once', async () => {
      const { initializePurchases } = await import('../../shared/services/purchases')
      
      await initializePurchases()
      await initializePurchases()
      
      expect(Purchases.configure).toHaveBeenCalledTimes(1)
    })

    it('should throw on configuration error', async () => {
      vi.mocked(Purchases.configure).mockRejectedValueOnce(new Error('Config failed'))
      
      vi.resetModules()
      const { initializePurchases } = await import('../../shared/services/purchases')
      
      await expect(initializePurchases()).rejects.toThrow('Config failed')
    })
  })

  describe('isPurchasesInitialized', () => {
    it('should return false before initialization', async () => {
      vi.resetModules()
      const { isPurchasesInitialized } = await import('../../shared/services/purchases')
      
      expect(isPurchasesInitialized()).toBe(false)
    })

    it('should return true after initialization', async () => {
      vi.resetModules()
      const { initializePurchases, isPurchasesInitialized } = await import('../../shared/services/purchases')
      
      await initializePurchases()
      
      expect(isPurchasesInitialized()).toBe(true)
    })
  })
})
