import { defineStore } from 'pinia';
import { client } from '~/utils/appwrite';
import { ref } from 'vue';
import type { RealtimeResponseEvent } from 'appwrite';

export const useRealtimeStore = defineStore('realtime', () => {
  const subscriptions = ref<Map<string, () => void>>(new Map());

  const register = (
    channel: string,
    fn: (response: RealtimeResponseEvent<unknown>) => void
  ) => {
    if (subscriptions.value.has(channel)) return;
    subscriptions.value.set(channel, client.subscribe(channel, fn));
  };

  return {
    register,
  };
});
