import { afterEach, describe, expect, it, vi } from 'vitest';
import { supportsBadging, updateAppBadge } from '../badges';

const originalSet = (navigator as any).setAppBadge;
const originalClear = (navigator as any).clearAppBadge;
const hadSet = 'setAppBadge' in navigator;
const hadClear = 'clearAppBadge' in navigator;

function restoreNavigator() {
  if (hadSet) {
    Object.defineProperty(navigator, 'setAppBadge', { configurable: true, value: originalSet });
  } else {
    delete (navigator as any).setAppBadge;
  }
  if (hadClear) {
    Object.defineProperty(navigator, 'clearAppBadge', { configurable: true, value: originalClear });
  } else {
    delete (navigator as any).clearAppBadge;
  }
}

describe('badges', () => {
  afterEach(() => {
    restoreNavigator();
  });

  it('sets the badge count when supported', async () => {
    const setAppBadge = vi.fn();
    Object.defineProperty(navigator, 'setAppBadge', { configurable: true, value: setAppBadge });
    Object.defineProperty(navigator, 'clearAppBadge', { configurable: true, value: vi.fn() });

    expect(supportsBadging()).toBe(true);
    await updateAppBadge(4);
    expect(setAppBadge).toHaveBeenCalledWith(4);
  });

  it('clears the badge when count is zero', async () => {
    const clearAppBadge = vi.fn();
    Object.defineProperty(navigator, 'setAppBadge', { configurable: true, value: vi.fn() });
    Object.defineProperty(navigator, 'clearAppBadge', { configurable: true, value: clearAppBadge });

    await updateAppBadge(0);
    expect(clearAppBadge).toHaveBeenCalled();
  });

  it('no-ops when unsupported', async () => {
    delete (navigator as any).setAppBadge;
    delete (navigator as any).clearAppBadge;
    expect(supportsBadging()).toBe(false);
    await updateAppBadge(3);
  });
});
