import { useState, useEffect, useCallback } from 'react';
import { supabase } from '../../lib/supabase';

export function useOrderComments(orderId) {
  const [comments, setComments] = useState([]);
  const [loading, setLoading] = useState(false);

  const fetch = useCallback(async () => {
    if (!orderId) return;
    const { data } = await supabase
      .from('order_comments')
      .select('*')
      .eq('order_id', orderId)
      .order('created_at', { ascending: true });
    setComments(data ?? []);
  }, [orderId]);

  useEffect(() => { fetch(); }, [fetch]);

  const addComment = async (author, body) => {
    setLoading(true);
    const { error } = await supabase.from('order_comments')
      .insert({ order_id: orderId, author, body });
    if (!error) await fetch();
    setLoading(false);
    return { error };
  };

  return { comments, loading, addComment };
}
