import { Routes, Route, Navigate } from 'react-router-dom';

import { useEffect } from 'react';

import LoginPage from './pages/LoginPage';

import PartnerAppRoutes from './PartnerAppRoutes';

import { handlePartnerWechatCallback, handlePartnerWechatLoginResult } from './lib/wechat-auth';

import { isLoggedIn } from './lib/api';

import { isWechatEnv } from './lib/weixin';

import { useLocation, useNavigate } from 'react-router-dom';



function WechatOAuthHandler() {

  const location = useLocation();

  const navigate = useNavigate();



  useEffect(() => {

    if (!isWechatEnv() || !location.search.includes('code=')) return;

    if (location.pathname === '/login') return;

    void handlePartnerWechatCallback()

      .then((result) => {

        if (!result || !handlePartnerWechatLoginResult(result)) return;

        const params = new URLSearchParams(location.search);

        params.delete('code');

        params.delete('state');

        const qs = params.toString();

        navigate(`${location.pathname}${qs ? `?${qs}` : ''}`, { replace: true });

      })

      .catch(() => {

        /* 页面内组件会提示 */

      });

  }, [location.pathname, location.search, navigate]);



  return null;

}



export default function App() {

  return (

    <>

      <WechatOAuthHandler />

      <Routes>

        <Route path="/login" element={<LoginPage />} />

        <Route path="/*" element={isLoggedIn() ? <PartnerAppRoutes /> : <Navigate to="/login" replace />} />

      </Routes>

    </>

  );

}

