// REQ-USR-004: RedirectIfAuthed —— 已登录访问 /login 回主页（BR2）
import { describe, it, expect } from 'vitest';
import { screen } from '@testing-library/react';
import { Routes, Route } from 'react-router-dom';
import { renderShell, type RenderShellOptions } from './renderShell';
import RedirectIfAuthed from '../../src/router/RedirectIfAuthed';

function LoginScreen() {
  return <div data-testid="login-screen">login-screen</div>;
}
function HomeSentinel() {
  return <div data-testid="home-sentinel">home-sentinel</div>;
}
function UsersSentinel() {
  return <div data-testid="users-sentinel">users-sentinel</div>;
}

function renderTree(
  initialEntries: { pathname: string; state?: unknown }[] | string[],
  preloadedAuth?: RenderShellOptions['preloadedAuth'],
) {
  return renderShell(
    <Routes>
      <Route
        path="/login"
        element={
          <RedirectIfAuthed>
            <LoginScreen />
          </RedirectIfAuthed>
        }
      />
      <Route path="/" element={<HomeSentinel />} />
      <Route path="/usr/users" element={<UsersSentinel />} />
    </Routes>,
    { initialEntries: initialEntries as never, preloadedAuth },
  );
}

const READY_USER = {
  token: 't',
  user: { id: 1, sUserName: '朱子纯', sUserType: '超级管理员', sLanguage: '中文' },
};

describe('RedirectIfAuthed', () => {
  it('renders children when unauthenticated', () => {
    renderTree(['/login'], { token: null, user: null });
    expect(screen.getByTestId('login-screen')).toBeInTheDocument();
  });

  it('redirects to / when already authenticated', () => {
    renderTree(['/login'], READY_USER);
    expect(screen.getByTestId('home-sentinel')).toBeInTheDocument();
    expect(screen.queryByTestId('login-screen')).not.toBeInTheDocument();
  });

  it('redirects to from when present', () => {
    renderTree([{ pathname: '/login', state: { from: '/usr/users' } }], READY_USER);
    expect(screen.getByTestId('users-sentinel')).toBeInTheDocument();
  });
});
