import { get } from 'svelte/store';
import { describe, expect, it, vi } from 'vitest';

import type { PicloudClient, RealtimeEvent, Unsubscribe } from '../src/index.js';
import { topicStore } from '../src/svelte/index.js';

type Cb = (e: RealtimeEvent<unknown>) => void;

describe('svelte topicStore', () => {
  it('subscribes on first subscriber and unsubscribes on last', () => {
    const unsubscribe = vi.fn();
    const holder: { cb: Cb | null } = { cb: null };
    const subscribe = vi.fn((_topic: string, cb: Cb): Unsubscribe => {
      holder.cb = cb;
      return unsubscribe as unknown as Unsubscribe;
    });
    const client = { subscribe } as unknown as PicloudClient;

    const store = topicStore<{ x: number }>(client, 'chat');
    // No SSE connection until someone subscribes (readable lifecycle).
    expect(subscribe).not.toHaveBeenCalled();

    let value: { x: number }[] = [];
    const stop = store.subscribe((v) => (value = v));
    expect(subscribe).toHaveBeenCalledTimes(1);

    holder.cb?.({ topic: 'chat', message: { x: 1 }, published_at: 't' });
    expect(value).toEqual([{ x: 1 }]);
    expect(get(store)).toEqual([{ x: 1 }]);

    stop();
    expect(unsubscribe).toHaveBeenCalledTimes(1);
  });
});
