import { useEffect, useState } from 'react';
import { database } from 'src/watermelondb';
import { Q } from '@nozbe/watermelondb';
import { Chat } from 'src/watermelondb/models';

export function useChatsListLive({ archived = 0 }: { archived?: number }) {
  const [chats, setChats] = useState<Chat[]>([]);

  useEffect(() => {
    const chatsCollection = database.get<Chat>('chats');

    let query = chatsCollection.query(Q.where('archive', archived), Q.where('removed', false));

    const sub = query
      .observeWithColumns(['pin', 'muted', 'unread_count', 'status', 'name'])
      .subscribe(setChats);

    return () => sub.unsubscribe();
  }, [archived]);

  return chats;
}
