/**
 * Hook: usePhotoSubmissionItems
 * Fetches photo items from relational tables for a given submission
 */

import { useState, useEffect } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { getErrorMessage } from '@/lib/errorHandler';
import type { PhotoSubmissionItem } from '@/types/photo-submissions';

interface UsePhotoSubmissionItemsResult {
  photos: PhotoSubmissionItem[];
  loading: boolean;
  error: string | null;
}

export function usePhotoSubmissionItems(
  submissionId: string | undefined
): UsePhotoSubmissionItemsResult {
  const [photos, setPhotos] = useState<PhotoSubmissionItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!submissionId) {
      setPhotos([]);
      setLoading(false);
      return;
    }

    fetchPhotoItems();
  }, [submissionId]);

  const fetchPhotoItems = async () => {
    if (!submissionId) return;

    setLoading(true);
    setError(null);

    try {
      // Step 1: Get photo_submission_id from submission_id
      const { data: photoSubmission, error: photoSubmissionError } = await supabase
        .from('photo_submissions')
        .select('id')
        .eq('submission_id', submissionId)
        .maybeSingle();

      if (photoSubmissionError) throw photoSubmissionError;
      if (!photoSubmission) {
        setPhotos([]);
        setLoading(false);
        return;
      }

      // Step 2: Get photo items using photo_submission_id
      const { data, error: itemsError } = await supabase
        .from('photo_submission_items')
        .select('*')
        .eq('photo_submission_id', photoSubmission.id)
        .order('order_index');

      if (itemsError) throw itemsError;

      setPhotos(data || []);
    } catch (error: unknown) {
      const errorMsg = getErrorMessage(error);
      console.error('Error fetching photo submission items:', errorMsg);
      setError(errorMsg);
      setPhotos([]);
    } finally {
      setLoading(false);
    }
  };

  return { photos, loading, error };
}
