// 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';

// react-router-dom 未公开 re-export InitialEntry，这里按其 MemoryRouter 接受的形态本地声明：
// 纯路径字符串，或携带 navigate state 的 Partial<Location>（FE-04 edit 预填数据流需要）。
type ShellInitialEntry = string | { pathname: string; search?: string; hash?: string; state?: unknown };
import { App as AntdApp, ConfigProvider } from 'antd';
import zhCN from 'antd/locale/zh_CN';
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 {
  // FE-04: 允许传 Partial<Location>（携带 navigate state），用于复刻 edit 单据经
  // navigate state 透传 presetUser 的数据流，不仅限纯路径字符串。
  initialEntries?: ShellInitialEntry[];
  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 locale={zhCN}>
        <AntdApp>
          <MemoryRouter initialEntries={options?.initialEntries ?? ['/']}>
            {ui}
          </MemoryRouter>
        </AntdApp>
      </ConfigProvider>
    </Provider>,
  );
  return {
    ...result,
    store,
    getState: () => store.getState() as RootState,
  };
}
