jest.mock('@revenuecat/purchases-capacitor', () => ({
  Purchases: {
    configure: jest.fn(),
    logIn: jest.fn(),
    logOut: jest.fn(),
    getOfferings: jest.fn(),
    purchasePackage: jest.fn(),
    restorePurchases: jest.fn(),
  },
}));

import {
  resolveAppUserId,
  isPurchaseCancelledError,
} from './revenueCat';
import { ACCESS_TOKEN_KEY } from '../auth/tokenStorage';

function makeJwt(payload: Record<string, unknown>): string {
  const body = btoa(JSON.stringify(payload))
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=+$/, '');
  return `hdr.${body}.sig`;
}

describe('revenueCat helpers', () => {
  beforeEach(() => {
    localStorage.clear();
  });

  it('prefers account.id for appUserID', () => {
    expect(resolveAppUserId({ id: 42 })).toBe('42');
  });

  it('falls back to JWT user_id claim', () => {
    localStorage.setItem(ACCESS_TOKEN_KEY, makeJwt({ user_id: 99, exp: 9999999999 }));
    expect(resolveAppUserId(null)).toBe('99');
  });

  it('returns null when no id available', () => {
    expect(resolveAppUserId(undefined)).toBeNull();
  });

  it('detects cancelled purchase errors', () => {
    expect(isPurchaseCancelledError({ userCancelled: true })).toBe(true);
    expect(isPurchaseCancelledError({ code: 1 })).toBe(true);
    expect(isPurchaseCancelledError({ message: 'boom' })).toBe(false);
  });
});
