// REQ-USR-003: 外壳 / 路由测试共享渲染工具（Provider + 真实 store + MemoryRouter + AntD App）
// 复用 FE-01 renderLogin.tsx 模式，扩展为可注入 auth 预置态（token/user）。
import type { ReactElement } from 'react';
import { render } from '@testing-library/react';
import { Provider } from 'react-redux';
import { MemoryRouter } from 'react-router-dom';
import { App as AntdApp, ConfigProvider } from 'antd';
import { configureStore } from '@reduxjs/toolkit';
import authReducer, { type AuthState } from '../../src/store/slices/authSlice';
import type { RootState } from '../../src/store/store';

/** 构建带 auth slice 的测试 store，可注入 token/user 预置态 */
export function makeShellStore(preloadedAuth?: Partial<AuthState>) {
  return configureStore({
    reducer: { auth: authReducer },
    preloadedState: preloadedAuth
      ? { auth: { token: null, user: null, ...preloadedAuth } }
      : undefined,
  });
}

export interface RenderShellOptions {
  initialEntries?: string[];
  preloadedAuth?: Partial<AuthState>;
  store?: ReturnType<typeof makeShellStore>;
}

export function renderShell(ui: ReactElement, options?: RenderShellOptions) {
  const store = options?.store ?? makeShellStore(options?.preloadedAuth);
  const result = render(
    <Provider store={store}>
      <ConfigProvider>
        <AntdApp>
          <MemoryRouter initialEntries={options?.initialEntries ?? ['/']}>
            {ui}
          </MemoryRouter>
        </AntdApp>
      </ConfigProvider>
    </Provider>,
  );
  return {
    ...result,
    store,
    getState: () => store.getState() as RootState,
  };
}
