// hooks/useAuth.tsx - React Hook 封装认证逻辑
'use client';

import { useState, useEffect } from 'react';
import { checkAuth, AuthInfo } from '../lib/auth';

export function useAuth() {
  const [authInfo, setAuthInfo] = useState<AuthInfo>({
    isAuthenticated: false,
  });
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // 组件挂载时检查认证状态
    const verifyAuth = async () => {
      console.log('[useAuth] Starting auth verification...');
      try {
        const info = await checkAuth();
        console.log('[useAuth] Auth info received:', info);
        setAuthInfo(info);
      } catch (error) {
        console.error('[useAuth] Auth verification failed:', error);
        setAuthInfo({
          isAuthenticated: false,
          message: '认证检查失败',
        });
      } finally {
        setLoading(false);
      }
    };

    verifyAuth();

    // 可选：定期检查认证状态
    const interval = setInterval(verifyAuth, 5 * 60 * 1000); // 每5分钟

    return () => clearInterval(interval);
  }, []);

  return {
    user: authInfo.user,
    isAuthenticated: authInfo.isAuthenticated || false,
    canAccessChat: authInfo.canAccessChat || false,
    message: authInfo.message,
    loading,
    refresh: async () => {
      setLoading(true);
      const info = await checkAuth();
      setAuthInfo(info);
      setLoading(false);
      return info;
    },
  };
}