import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, expect, test, vi } from 'vitest';
import UsersPage from './UsersPage';

const mocks = vi.hoisted(() => ({
  adminUsers: vi.fn(),
  vehicleCoverage: vi.fn(),
  createCustomerUser: vi.fn(),
  updateCustomerUser: vi.fn()
}));

vi.mock('../../api/client', () => ({ api: mocks }));

afterEach(() => {
  cleanup();
  Object.values(mocks).forEach((mock) => mock.mockReset());
});

test('deduplicates vehicle candidates by VIN and renders granted vehicles plate first', async () => {
  mocks.adminUsers.mockResolvedValue([{
    id: 7,
    username: 'customer-east',
    displayName: '华东客户',
    userType: 'customer',
    status: 'enabled',
    customerRef: '',
    tenantRef: '',
    authProvider: 'local',
    menuKeys: ['monitor'],
    vehicleVins: ['VIN001'],
    vehicles: [{ vin: 'VIN001', plate: '粤A11111', validFrom: '2026-06-05T00:00:00+08:00', sourceSystem: 'manual', grantedBy: '平台管理员' }],
    grantHistory: [{ id: 1, vin: 'VIN001', plate: '粤A11111', validFrom: '2026-06-05T00:00:00+08:00', sourceSystem: 'manual', grantedBy: '平台管理员', revokedBy: '', createdAt: '2026-07-16T00:00:00Z', updatedAt: '2026-07-16T00:00:00Z' }],
    createdAt: '2026-07-16T00:00:00Z',
    updatedAt: '2026-07-16T00:00:00Z'
  }]);
  const duplicatedVehicle = { vin: 'VIN002', plate: '粤A22222', protocols: ['GB32960', 'JT808'] };
  mocks.vehicleCoverage.mockResolvedValue({ items: [duplicatedVehicle, duplicatedVehicle], total: 1, limit: 20, offset: 0 });
  const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });

  render(<QueryClientProvider client={client}><UsersPage /></QueryClientProvider>);

  fireEvent.click(await screen.findByRole('button', { name: /华东客户/ }));
  expect((await screen.findByRole('button', { name: '移除 粤A11111' })).closest('article')).toHaveTextContent('粤A11111VIN001');

  fireEvent.change(screen.getByRole('textbox', { name: '按车牌或 VIN 搜索' }), { target: { value: '粤A22222' } });
  await waitFor(() => expect(mocks.vehicleCoverage).toHaveBeenCalled());
  const candidates = await screen.findAllByRole('button', { name: /粤A22222.*VIN002.*选择/ });
  expect(candidates).toHaveLength(1);
  expect((mocks.vehicleCoverage.mock.calls[0][0] as URLSearchParams).get('keyword')).toBe('粤A22222');

  fireEvent.click(candidates[0]);
  expect((await screen.findByRole('button', { name: '移除 粤A22222' })).closest('article')).toHaveTextContent('粤A22222VIN002');
});

test('submits per-vehicle authorization interval instead of only a VIN list', async () => {
  mocks.adminUsers.mockResolvedValue([{
    id: 7, username: 'customer-east', displayName: '华东客户', userType: 'customer', status: 'enabled',
    customerRef: '', tenantRef: '', authProvider: 'local', menuKeys: ['statistics'], vehicleVins: ['VIN001'],
    vehicles: [{ vin: 'VIN001', plate: '粤A11111', validFrom: '2026-07-16T14:08:18+08:00', sourceSystem: 'manual', grantedBy: '平台管理员' }],
    grantHistory: [], createdAt: '2026-07-16T00:00:00Z', updatedAt: '2026-07-16T00:00:00Z'
  }]);
  mocks.updateCustomerUser.mockResolvedValue({ id: 7 });
  const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
  render(<QueryClientProvider client={client}><UsersPage /></QueryClientProvider>);
  fireEvent.click(await screen.findByRole('button', { name: /华东客户/ }));
  fireEvent.change(await screen.findByLabelText('粤A11111 启用时间'), { target: { value: '2026-06-05T00:00' } });
  fireEvent.click(screen.getByRole('button', { name: '保存权限' }));
  await waitFor(() => expect(mocks.updateCustomerUser).toHaveBeenCalled());
  expect(mocks.updateCustomerUser.mock.calls[0][1]).toMatchObject({
    vehicleVins: ['VIN001'],
    vehicleGrants: [{ vin: 'VIN001', validFrom: '2026-06-05T00:00', validTo: '' }]
  });
});
