import { flushAnalyticsQueue, identifyAccount, identifyUser, trackEvent } from './analytics';
import { Account } from '../data';

describe('analytics event helpers', () => {
  const originalEnv = process.env;

  beforeEach(() => {
    localStorage.clear();
    process.env = { ...originalEnv, REACT_APP_DEPLOY_ENV: 'production' };
    delete (window as { tianji?: unknown }).tianji;
  });

  afterEach(() => {
    process.env = { ...originalEnv };
    delete (window as { tianji?: unknown }).tianji;
  });

  it('does not track custom events without consent', () => {
    const track = jest.fn();
    window.tianji = { track, identify: jest.fn() };

    trackEvent('Login Success');
    expect(track).not.toHaveBeenCalled();
  });

  it('tracks custom events when consent granted', () => {
    localStorage.setItem('hesychia_analytics_consent_v1', 'granted');
    const track = jest.fn();
    window.tianji = { track, identify: jest.fn() };

    trackEvent('Login Success', { method: 'password' });
    expect(track).toHaveBeenCalledWith('Login Success', { method: 'password' });
  });

  it('queues events until tianji is ready then flushes after consent', () => {
    localStorage.setItem('hesychia_analytics_consent_v1', 'granted');

    trackEvent('Checkout Started');
    const track = jest.fn();
    window.tianji = { track, identify: jest.fn() };
    flushAnalyticsQueue();

    expect(track).toHaveBeenCalledWith('Checkout Started', undefined);
  });

  it('identify requires consent', () => {
    const identify = jest.fn();
    window.tianji = { track: jest.fn(), identify };

    identifyUser({ userId: 'u1' });
    expect(identify).not.toHaveBeenCalled();

    localStorage.setItem('hesychia_analytics_consent_v1', 'granted');
    identifyUser({ userId: 'u1' });
    expect(identify).toHaveBeenCalledWith({ userId: 'u1' });
  });

  it('identifyAccount sends email as userId without names', () => {
    localStorage.setItem('hesychia_analytics_consent_v1', 'granted');
    const identify = jest.fn();
    window.tianji = { track: jest.fn(), identify };

    identifyAccount(
      new Account({
        email: 'user@example.com',
        first_name: 'Secret',
        last_name: 'Name',
        is_company_manager: true,
        company: { id: 42, name: 'Acme' },
      }),
    );

    expect(identify).toHaveBeenCalledWith({
      userId: 'user@example.com',
      companyId: 42,
      isCompanyManager: true,
    });
    expect(JSON.stringify(identify.mock.calls[0][0])).not.toMatch(/Secret|Name|Acme/);
  });
});
