import { useMutation } from '@tanstack/react-query';

import { useSupabase } from './use-supabase';

export function useSignOut() {
  const client = useSupabase();

  return useMutation({
    mutationFn: async () => {
      try {
        try {
          const { medusaLogout } = await import(
            '../../../features/medusa-storefront/src/lib/data/customer'
          );
          await medusaLogout(undefined, false);
        } catch (medusaError) {
          console.warn('Medusa logout failed or not available:', medusaError);
        }

        const { error } = await client.auth.signOut();
        if (error) {
          throw error;
        }
      } catch (error) {
        console.error('Logout error:', error);
        throw error;
      }
    },
  });
}
