import { useState, useEffect, useCallback, useRef } from 'react'; import { useToast } from './use-toast'; interface EmailFetchState { email: any | null; loading: boolean; error: string | null; } interface UseEmailFetchProps { onEmailLoaded?: (email: any) => 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) => { try { // Cancel any in-flight request if (abortControllerRef.current) { abortControllerRef.current.abort(); } // Create new abort controller abortControllerRef.current = new AbortController(); // Validate parameters validateFetchParams(emailId, accountId, folder); setState(prev => ({ ...prev, loading: true, error: null })); const response = await fetch( `/api/courrier/${emailId}?accountId=${encodeURIComponent(accountId)}&folder=${encodeURIComponent(folder)}`, { signal: abortControllerRef.current.signal } ); if (!response.ok) { const errorData = await response.json(); throw new Error(errorData.error || 'Failed to fetch email'); } const data = await response.json(); if (!data) { throw new Error('Email not found'); } setState({ email: data, loading: false, error: null }); onEmailLoaded?.(data); // Mark as read if not already if (!data.flags?.seen) { try { await fetch(`/api/courrier/${emailId}/mark-read`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'mark-read' }) }); } catch (err) { console.error('Error marking email as read:', err); } } } catch (err) { // Don't set error if request was aborted if (err.name === 'AbortError') { return; } const errorMessage = err instanceof Error ? err.message : 'Failed to load email'; setState(prev => ({ ...prev, loading: false, error: errorMessage })); onError?.(errorMessage); // Show toast for user feedback toast({ title: 'Error', description: errorMessage, variant: 'destructive' }); } }, [onEmailLoaded, onError, toast]); // Cleanup on unmount useEffect(() => { return () => { if (abortControllerRef.current) { abortControllerRef.current.abort(); } }; }, []); return { ...state, fetchEmail }; }