
import { supabase } from "@/integrations/supabase/client";
import { Comment } from "@/types";
import { useAuth } from "@/contexts/AuthContext";
import { normalizeCommentContent } from "@/services/commentGuards";
import { mapCommentFromDB } from "@/utils/tripStepMappers";
import { useCallback } from "react";

export function useSupabaseComments() {
  const { currentUser } = useAuth();

  const addStepComment = useCallback(async (tripId: string, stepId: string, commentData: Omit<Comment, "id" | "userId" | "userName" | "createdAt">) => {
    if (!currentUser) {
      throw new Error("Utilisateur non connecté");
    }

    const content = normalizeCommentContent(commentData.content);

    // Vérifier l'accès au voyage pour ce step
    const { data: tripStep, error: stepError } = await supabase
      .from('trip_steps')
      .select('trip_id')
      .eq('id', stepId)
      .eq('trip_id', tripId)
      .maybeSingle();

    if (stepError) throw stepError;
    if (!tripStep) throw new Error("Étape inaccessible ou voyage incohérent.");

    // Insérer le commentaire
    const { data: newComment, error } = await supabase
      .from('comments')
      .insert({
        step_id: stepId,
        content,
      })
      .select('id, trip_id, step_id, user_id, user_name, content, created_at')
      .single();

    if (error) throw error;
    if (newComment.trip_id !== tripId || newComment.step_id !== stepId) {
      throw new Error("Le commentaire persisté ne correspond pas à l'étape demandée.");
    }
    return mapCommentFromDB(newComment);
  }, [currentUser]);

  const getStepComments = useCallback(async (stepId: string) => {
    const { data: comments, error } = await supabase
      .from('comments')
      .select('id, trip_id, user_id, user_name, content, created_at, step_id')
      .eq('step_id', stepId)
      .order('created_at', { ascending: true })
      .order('id', { ascending: true });

    if (error) throw error;
    return comments.map(mapCommentFromDB);
  }, []);

  return {
    addStepComment,
    getStepComments
  };
}
