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

export function useMessageSearch(search: string) {
  const [results, setResults] = useState<
    {
      chatKey: string;
      messageId: number;
      text: string;
      sentAt: number;
    }[]
  >([]);

  useEffect(() => {
    let cancelled = false;

    async function run() {
      if (!search.trim()) {
        setResults([]);
        return;
      }

      const rows = await database
        .get<Message>('messages')
        .query(Q.where('text', Q.like(`%${search}%`)), Q.sortBy('sent_at', Q.desc), Q.take(100))
        .fetch();

      if (cancelled) return;

      setResults(
        rows.map((m) => ({
          chatKey: m.chatKey,
          messageId: m.messageId!,
          text: m.text ?? '',
          sentAt: m.sentAt as any
        }))
      );
    }

    run();
    return () => {
      cancelled = true;
    };
  }, [search]);

  return results;
}
