import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { resetStore } from '../test/storeTestUtils';
import { useStore } from '../store/useStore';
import { Login } from './Login';

const apiMock = vi.hoisted(() => ({
  login: vi.fn(),
}));

vi.mock('../lib/api', () => ({
  login: apiMock.login,
}));

describe('Login', () => {
  beforeEach(() => {
    resetStore();
    vi.clearAllMocks();
  });

  it('logs in with the development credentials and stores the token', async () => {
    apiMock.login.mockResolvedValueOnce({ token: 'fake-jwt-token-for-admin' });

    render(<Login />);
    fireEvent.click(screen.getByRole('button', { name: '安全登录' }));

    await waitFor(() => expect(apiMock.login).toHaveBeenCalledWith('admin', '123456'));
    expect(useStore.getState().isAuthenticated).toBe(true);
    expect(localStorage.getItem('token')).toBe('fake-jwt-token-for-admin');
  });

  it('shows backend login errors', async () => {
    apiMock.login.mockRejectedValueOnce({ response: { data: { detail: 'Invalid credentials' } } });

    render(<Login />);
    fireEvent.change(screen.getByDisplayValue('admin'), { target: { value: 'bad' } });
    fireEvent.click(screen.getByRole('button', { name: '安全登录' }));

    expect(await screen.findByText('Invalid credentials')).toBeInTheDocument();
    expect(useStore.getState().isAuthenticated).toBe(false);
  });
});
