import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { MemoryRouter, Routes, Route } from 'react-router-dom';
import { Provider } from 'react-redux';
import { configureStore } from '@reduxjs/toolkit';
import authReducer, { setSession } from '../store/slices/authSlice';
import RequireAuth from './RequireAuth';

function makeStore(preloadedToken: string | null = null) {
  const store = configureStore({ reducer: { auth: authReducer } });
  if (preloadedToken) {
    store.dispatch(
      setSession({
        accessToken: preloadedToken,
        userInfo: {
          userId: 1,
          username: 'alice',
          userType: 'NORMAL',
          language: 'zh-CN',
          companyCode: 'HQ',
        },
      }),
    );
  }
  return store;
}

function renderWithRouter(store: ReturnType<typeof makeStore>, initialEntry: string) {
  return render(
    <Provider store={store}>
      <MemoryRouter initialEntries={[initialEntry]}>
        <Routes>
          <Route
            path="/users"
            element={
              <RequireAuth>
                <div data-testid="protected">PROTECTED</div>
              </RequireAuth>
            }
          />
          <Route path="/login" element={<div data-testid="login">LOGIN</div>} />
        </Routes>
      </MemoryRouter>
    </Provider>,
  );
}

describe('RequireAuth', () => {
  it('redirects to /login when no token', () => {
    renderWithRouter(makeStore(null), '/users');
    expect(screen.getByTestId('login')).toBeInTheDocument();
    expect(screen.queryByTestId('protected')).toBeNull();
  });

  it('renders children when token present', () => {
    renderWithRouter(makeStore('jwt'), '/users');
    expect(screen.getByTestId('protected')).toBeInTheDocument();
  });
});
