import { useEffect } from 'react';
import { supabase } from '@/lib/supabase';
import { useAuthStore } from '@/stores/auth-store';

export function AuthProvider({ children }: { children: React.ReactNode }) {
    const { auth } = useAuthStore();

    useEffect(() => {
        // 监听 Supabase 身份状态变化
        const { data: { subscription } } = supabase.auth.onAuthStateChange((event, session) => {
            console.log('🔄 Supabase Auth Event:', event);

            if (session?.user) {
                // 同步 Supabase 用户到我们的 store
                auth.setUser({
                    accountNo: session.user.id,
                    email: session.user.email || '',
                    role: ['admin'], // 暂定为 admin
                    exp: session.expires_at ? session.expires_at * 1000 : Date.now() + 86400000,
                });
                auth.setAccessToken(session.access_token);
            } else if (event === 'SIGNED_OUT') {
                auth.reset();
            }
        });

        return () => {
            subscription.unsubscribe();
        };
    }, [auth]);

    return <>{children}</>;
}
