import { describe, it, expect, vi, beforeEach } from 'vitest';
import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

const messageSpy = { success: vi.fn(), error: vi.fn() };
vi.mock('antd', async () => {
  const actual = await vi.importActual<typeof import('antd')>('antd');
  return {
    ...actual,
    App: Object.assign(actual.App, { useApp: () => ({ message: messageSpy }) }),
  };
});

vi.mock('../../src/api/usrApi', () => ({
  fetchCompanies: vi.fn(),
  login: vi.fn(),
}));

import { fetchCompanies, login } from '../../src/api/usrApi';
import LoginPage from '../../src/pages/usr/Login/LoginPage';
import { ApiError, NETWORK_ERROR_CODE } from '../../src/api/request';
import { renderWithProviders } from './renderLogin';

const mockedFetch = fetchCompanies as unknown as ReturnType<typeof vi.fn>;
const mockedLogin = login as unknown as ReturnType<typeof vi.fn>;

async function fillAndSubmit() {
  const user = userEvent.setup();
  await user.type(screen.getByPlaceholderText('请输入你的用户名'), 'admin');
  await user.type(screen.getByPlaceholderText('请输入你的密码'), 'secret');
  await user.click(screen.getByRole('button', { name: /登\s*录/ }));
  return user;
}

describe('LoginPage 登录失败错误码分流', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    localStorage.clear();
    mockedFetch.mockResolvedValue([{ id: 1, sCompanyName: '甲公司', sVersion: '标准版' }]);
  });

  it('40101 shows 用户名或密码错误 and clears+focuses password', async () => {
    mockedLogin.mockRejectedValue(new ApiError(40101, '认证失败'));
    renderWithProviders(<LoginPage />);
    expect(await screen.findByText('甲公司（标准版）')).toBeInTheDocument();
    await fillAndSubmit();
    await waitFor(() => expect(messageSpy.error).toHaveBeenCalledWith('用户名或密码错误'));
    const password = screen.getByPlaceholderText('请输入你的密码') as HTMLInputElement;
    await waitFor(() => expect(password.value).toBe(''));
    expect(document.activeElement).toBe(password);
  });

  it('40302 shows 该账号已被禁用，请联系管理员', async () => {
    mockedLogin.mockRejectedValue(new ApiError(40302, '已禁用'));
    renderWithProviders(<LoginPage />);
    expect(await screen.findByText('甲公司（标准版）')).toBeInTheDocument();
    await fillAndSubmit();
    await waitFor(() =>
      expect(messageSpy.error).toHaveBeenCalledWith('该账号已被禁用，请联系管理员'),
    );
  });

  it('42901 shows 登录尝试过于频繁，请稍后再试 and clears password', async () => {
    mockedLogin.mockRejectedValue(new ApiError(42901, '限流'));
    renderWithProviders(<LoginPage />);
    expect(await screen.findByText('甲公司（标准版）')).toBeInTheDocument();
    await fillAndSubmit();
    await waitFor(() =>
      expect(messageSpy.error).toHaveBeenCalledWith('登录尝试过于频繁，请稍后再试'),
    );
    const password = screen.getByPlaceholderText('请输入你的密码') as HTMLInputElement;
    await waitFor(() => expect(password.value).toBe(''));
  });

  it('40001 shows 请填写用户名、密码并选择版本', async () => {
    mockedLogin.mockRejectedValue(new ApiError(40001, '参数错误'));
    renderWithProviders(<LoginPage />);
    expect(await screen.findByText('甲公司（标准版）')).toBeInTheDocument();
    await fillAndSubmit();
    await waitFor(() =>
      expect(messageSpy.error).toHaveBeenCalledWith('请填写用户名、密码并选择版本'),
    );
  });

  it('network error shows 网络异常，请稍后重试', async () => {
    mockedLogin.mockRejectedValue(new ApiError(NETWORK_ERROR_CODE, '网络异常'));
    renderWithProviders(<LoginPage />);
    expect(await screen.findByText('甲公司（标准版）')).toBeInTheDocument();
    await fillAndSubmit();
    await waitFor(() => expect(messageSpy.error).toHaveBeenCalledWith('网络异常，请稍后重试'));
  });

  it('button recovers clickable and username/version preserved after failure', async () => {
    mockedLogin.mockRejectedValue(new ApiError(40101, '认证失败'));
    renderWithProviders(<LoginPage />);
    expect(await screen.findByText('甲公司（标准版）')).toBeInTheDocument();
    await fillAndSubmit();
    await waitFor(() => expect(messageSpy.error).toHaveBeenCalled());
    const submit = screen.getByRole('button', { name: /登\s*录/ });
    await waitFor(() => expect(submit).not.toHaveClass('ant-btn-loading'));
    expect(submit).not.toBeDisabled();
    // 用户名保留
    expect((screen.getByPlaceholderText('请输入你的用户名') as HTMLInputElement).value).toBe('admin');
    // 版本保留（单项自动选中仍在）
    expect(screen.getByText('甲公司（标准版）')).toBeInTheDocument();
  });
});
