import { useQueryClient } from '@tanstack/react-query'; import { useEffect, useRef, useState } from 'react'; import { getCurrentUserId, pb } from '@/services/pocketbase'; import type { NoteRecord } from '@/types/collections'; /** * Note libre : hydrate depuis le bundle `useBienDetail` (évite un 2e GET sur notes_biens). */ export function useNoteLibre(bienId: string | undefined, notesFromBundle: NoteRecord[] | undefined) { const uid = getCurrentUserId(); const queryClient = useQueryClient(); const [draft, setDraftState] = useState(''); const [hydrated, setHydrated] = useState(false); const noteIdRef = useRef(null); const userEdited = useRef(false); const prevBienId = useRef(undefined); useEffect(() => { if (prevBienId.current !== bienId) { prevBienId.current = bienId; userEdited.current = false; } }, [bienId]); useEffect(() => { if (!bienId || !uid) { setHydrated(false); return; } if (notesFromBundle === undefined) { setHydrated(false); return; } const libre = notesFromBundle.find((r) => { const t = r.type_note as string | undefined; return t == null || t === '' || t === 'libre'; }) ?? null; noteIdRef.current = libre?.id ?? null; if (!userEdited.current) { setDraftState(libre?.contenu ?? ''); } setHydrated(true); }, [bienId, uid, notesFromBundle]); useEffect(() => { if (!bienId || !uid || !hydrated || !userEdited.current) return; const t = setTimeout(() => { void (async () => { try { if (!draft.trim()) return; if (noteIdRef.current) { await pb.collection('notes_biens').update(noteIdRef.current, { contenu: draft }); } else { const c = await pb.collection('notes_biens').create({ user: uid, bien: bienId, contenu: draft, type_note: 'libre', }); noteIdRef.current = c.id; } void queryClient.invalidateQueries({ queryKey: ['bien_detail', bienId] }); } catch { /* ignore autosave */ } })(); }, 500); return () => clearTimeout(t); }, [draft, bienId, uid, hydrated, queryClient]); const setDraft = (text: string) => { userEdited.current = true; setDraftState(text); }; return { draft, setDraft, hydrated }; }