import { describe, expect, it } from 'vitest';
import {
  getTransferState,
  setTransferState,
  subscribeTransferState,
} from './transferStore';

describe('transferStore', () => {
  it('patches state, notifies subscribers, and survives unsubscribe/resubscribe', () => {
    // The whole point of the store: a consumer that unmounts (unsubscribes)
    // and remounts still sees the in-flight transfer, unlike component state.
    setTransferState({ transfer: null, pullingPaths: null });

    let seen = 0;
    const unsubscribe = subscribeTransferState(() => {
      seen += 1;
    });

    const transfer = { kind: 'pull', path: 'a.txt', done: 1, total: 10 };
    setTransferState({ transfer });
    expect(seen).toBe(1);
    expect(getTransferState().transfer).toEqual(transfer);
    // Patch semantics: untouched keys survive.
    setTransferState({ pullingPaths: new Set(['a.txt']) });
    expect(getTransferState().transfer).toEqual(transfer);

    unsubscribe(); // simulated unmount mid-transfer
    setTransferState({ transfer: { ...transfer, done: 5 } });
    expect(seen).toBe(2); // no longer notified...

    // ...but a fresh subscriber (remount) reads the live in-flight state.
    const states = [];
    const unsubscribe2 = subscribeTransferState(() => states.push(getTransferState()));
    expect(getTransferState().transfer.done).toBe(5);
    setTransferState({ transfer: null, pullingPaths: null });
    expect(states.at(-1).transfer).toBeNull();
    unsubscribe2();
  });
});
