import { useState, useEffect, useCallback } from 'react'; import { resetAllData } from '@/contexts/budget/storage'; import { resetAllStorageData } from '@/utils/storageUtils'; import { clearCloudData } from '@/utils/sync/clearCloudData'; import { useAuth } from '@/contexts/auth'; export const useDataInitialization = (resetBudgetData?: () => void) => { const [isInitialized, setIsInitialized] = useState(false); const { user } = useAuth(); // 모든 데이터 초기화 함수 const initializeAllData = useCallback(async () => { // 중요: 이미 방문한 적이 있으면 절대 초기화하지 않음 const hasVisitedBefore = localStorage.getItem('hasVisitedBefore') === 'true'; if (hasVisitedBefore) { console.log('이미 앱을 방문한 적이 있으므로 데이터를 초기화하지 않습니다.'); setIsInitialized(true); return true; } console.log('첫 방문: 모든 데이터 초기화 시작'); // 현재 dontShowWelcome 값 백업 const dontShowWelcomeValue = localStorage.getItem('dontShowWelcome'); console.log('useDataInitialization - 초기화 전 dontShowWelcome 값:', dontShowWelcomeValue); try { // 로그인 상태라면 클라우드 데이터도 초기화 (첫 방문 시) if (user) { console.log('로그인 상태: 클라우드 데이터도 초기화 시도'); await clearCloudData(user.id); } // 모든 데이터 완전히 삭제 및 초기화 (한 번만 실행) resetAllData(); resetAllStorageData(); // 컨텍스트 데이터 리셋 (필요한 경우) if (resetBudgetData) { resetBudgetData(); } // 초기화 후 dontShowWelcome 값 확인 const afterResetValue = localStorage.getItem('dontShowWelcome'); console.log('useDataInitialization - 초기화 후 dontShowWelcome 값:', afterResetValue); // 값이 유지되지 않았다면 복원 if (dontShowWelcomeValue && afterResetValue !== dontShowWelcomeValue) { console.log('useDataInitialization - dontShowWelcome 값 복원:', dontShowWelcomeValue); localStorage.setItem('dontShowWelcome', dontShowWelcomeValue); } console.log('모든 데이터 초기화 완료'); return true; } catch (error) { console.error('데이터 초기화 중 오류 발생:', error); return false; } }, [resetBudgetData, user]); // 분석 페이지 데이터 초기화 함수 const clearAllAnalyticsData = useCallback(() => { try { // 분석 관련 데이터만 선택적으로 삭제 (전체 데이터는 건드리지 않음) const analyticsKeys = [ 'analytics', 'monthlyTotals', 'chartData', 'expenseHistory', 'budgetHistory', 'categorySpending', 'monthlyData', 'expenseData', 'analyticData' ]; analyticsKeys.forEach(key => { localStorage.removeItem(key); }); // 월간, 차트, 분석 관련 키워드가 포함된 항목만 삭제 for (let i = localStorage.length - 1; i >= 0; i--) { const key = localStorage.key(i); if (key && ( key.includes('month') || key.includes('chart') || key.includes('analytics') || key.includes('expense') || key.includes('budget') || key.includes('total') ) && // 핵심 데이터는 건드리지 않도록 제외 !key.includes('budgetData') && !key.includes('transactions') && !key.includes('categoryBudgets')) { console.log(`분석 데이터 삭제: ${key}`); localStorage.removeItem(key); } } return true; } catch (error) { console.error('분석 데이터 초기화 중 오류:', error); return false; } }, []); // 데이터 초기화 실행 - 첫 방문시에만 useEffect(() => { if (!isInitialized) { // 이미 방문한 적이 있는지 체크 (이미 있다면 초기화하지 않음) const hasVisitedBefore = localStorage.getItem('hasVisitedBefore') === 'true'; if (hasVisitedBefore) { console.log('이미 방문 기록이 있어 초기화를 건너뜁니다.'); setIsInitialized(true); } else { initializeAllData().then(result => { setIsInitialized(result); }); } } // 첫 방문 여부 체크용 키 설정 (항상 true로 설정) localStorage.setItem('hasVisitedBefore', 'true'); }, [isInitialized, initializeAllData]); return { isInitialized, initializeAllData, clearAllAnalyticsData }; };