import {
  appHref,
  isNativePlatform,
  redirectToAppPath,
} from './nativePlatform';

describe('nativePlatform', () => {
  const originalCapacitor = window.Capacitor;
  const originalLocation = window.location;

  afterEach(() => {
    if (originalCapacitor === undefined) {
      delete window.Capacitor;
    } else {
      window.Capacitor = originalCapacitor;
    }
    Object.defineProperty(window, 'location', {
      configurable: true,
      value: originalLocation,
    });
  });

  describe('isNativePlatform', () => {
    it('returns false when Capacitor missing', () => {
      delete window.Capacitor;
      expect(isNativePlatform()).toBe(false);
    });

    it('uses Capacitor.isNativePlatform when present', () => {
      window.Capacitor = {
        isNativePlatform: () => true,
      };
      expect(isNativePlatform()).toBe(true);
    });

    it('falls back to Capacitor.isNative', () => {
      window.Capacitor = { isNative: true };
      expect(isNativePlatform()).toBe(true);
    });
  });

  describe('appHref', () => {
    it('returns plain path on web', () => {
      delete window.Capacitor;
      expect(appHref('/signin/')).toBe('/signin/');
    });

    it('returns hash path on native', () => {
      window.Capacitor = { isNativePlatform: () => true };
      expect(appHref('/signin/')).toBe('/#/signin/');
    });
  });

  describe('redirectToAppPath', () => {
    it('sets location.href on web', () => {
      delete window.Capacitor;
      const hrefSetter = jest.fn();
      Object.defineProperty(window, 'location', {
        configurable: true,
        value: {
          ...originalLocation,
          set href(v) {
            hrefSetter(v);
          },
          get href() {
            return '';
          },
        },
      });
      redirectToAppPath('/signin/');
      expect(hrefSetter).toHaveBeenCalledWith('/signin/');
    });

    it('sets location.hash on native', () => {
      window.Capacitor = { isNativePlatform: () => true };
      let hashValue = '';
      Object.defineProperty(window, 'location', {
        configurable: true,
        value: {
          get hash() {
            return hashValue;
          },
          set hash(v) {
            hashValue = v;
          },
        },
      });
      redirectToAppPath('/signin/');
      expect(hashValue).toBe('#/signin/');
    });
  });
});
