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 RequireSuperAdmin from './RequireSuperAdmin';

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

function renderRoutes(store: ReturnType<typeof makeStore>, entry: string) {
  return render(
    <Provider store={store}>
      <MemoryRouter initialEntries={[entry]}>
        <Routes>
          <Route
            path="/users"
            element={
              <RequireSuperAdmin>
                <div data-testid="admin-only">ADMIN</div>
              </RequireSuperAdmin>
            }
          />
          <Route path="/login" element={<div data-testid="login">LOGIN</div>} />
        </Routes>
      </MemoryRouter>
    </Provider>,
  );
}

describe('RequireSuperAdmin', () => {
  it('no token → redirects to /login', () => {
    renderRoutes(makeStore(), '/users');
    expect(screen.getByTestId('login')).toBeInTheDocument();
  });

  it('NORMAL user token → shows 403 Result', () => {
    renderRoutes(makeStore({ token: 'jwt', userType: 'NORMAL' }), '/users');
    expect(screen.getByTestId('forbidden-result')).toBeInTheDocument();
    expect(screen.queryByTestId('admin-only')).toBeNull();
  });

  it('SUPER_ADMIN token → renders children', () => {
    renderRoutes(makeStore({ token: 'jwt', userType: 'SUPER_ADMIN' }), '/users');
    expect(screen.getByTestId('admin-only')).toBeInTheDocument();
  });
});
