import { useState, useEffect, useCallback, useRef } from 'react'; import { useToast } from './use-toast'; import { EmailMessage, EmailContent } from '@/types/email'; import { processContentWithDirection } from '@/lib/utils/text-direction'; interface EmailFetchState { email: EmailMessage | null; loading: boolean; error: string | null; } interface UseEmailFetchProps { onEmailLoaded?: (email: EmailMessage) => void; onError?: (error: string) => void; } export function useEmailFetch({ onEmailLoaded, onError }: UseEmailFetchProps = {}) { const [state, setState] = useState({ email: null, loading: false, error: null }); const abortControllerRef = useRef(null); const { toast } = useToast(); // Validate email fetch parameters const validateFetchParams = (emailId: string, accountId: string, folder: string) => { if (!emailId || typeof emailId !== 'string') { throw new Error('Invalid email ID'); } if (!accountId || typeof accountId !== 'string') { throw new Error('Invalid account ID'); } if (!folder || typeof folder !== 'string') { throw new Error('Invalid folder'); } // Validate UID format if (!/^\d+$/.test(emailId)) { throw new Error('Email ID must be a numeric UID'); } }; // Fetch email with proper error handling and cancellation const fetchEmail = useCallback(async (emailId: string, accountId: string, folder: string) => { if (!emailId || !accountId || !folder) { console.error('Missing required parameters for fetchEmail'); return; } // Abort any previous request if (abortControllerRef.current) { abortControllerRef.current.abort(); } abortControllerRef.current = new AbortController(); setState(prev => ({ ...prev, loading: true, error: null })); try { const response = await fetch( `/api/courrier/${emailId}?accountId=${encodeURIComponent(accountId)}&folder=${encodeURIComponent(folder)}`, { signal: abortControllerRef.current?.signal } ); if (!response.ok) { throw new Error(`Failed to fetch email: ${response.statusText}`); } const data = await response.json(); // Create a valid email message object with required fields const processContent = (data: any): EmailContent => { // Extract initial content from all possible sources let initialContent: any = {}; if (typeof data.content === 'object' && data.content) { // Use content object directly if available initialContent = data.content; } else { // Build content object from separate properties if (typeof data.content === 'string') { // Check if content appears to be HTML if (data.content.includes('<') && (data.content.includes(' ({ ...prev, loading: false, error: errorMessage })); onError?.(errorMessage); toast({ title: 'Error', description: errorMessage, variant: 'destructive' }); } }, [onEmailLoaded, onError, toast]); // Cleanup on unmount useEffect(() => { return () => { if (abortControllerRef.current) { abortControllerRef.current.abort(); } }; }, []); return { ...state, fetchEmail }; }