import { describe, it, expect, beforeEach, vi } from 'vitest';
import { screen, waitFor } from '@testing-library/react';
import { renderWithProviders } from '../test/utils';

vi.mock('../lib/api', () => ({
  api: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), put: vi.fn(), delete: vi.fn() },
  ApiError: class extends Error {},
}));

vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));

import { api } from '../lib/api';
import PlanAccuracyPage from './PlanAccuracyPage';

const get = api.get as ReturnType<typeof vi.fn>;

const rows = [
  {
    service_uuid: 's1',
    service_name: 'لیزر فول‌بادی',
    sample_size: 4,
    planned_minutes: 60,
    actual_minutes: 90,
    deviation_percent: 50,
    severity: 'high' as const,
  },
  {
    service_uuid: 's2',
    service_name: 'مشاوره',
    sample_size: 5,
    planned_minutes: 30,
    actual_minutes: 29,
    deviation_percent: -3,
    severity: 'none' as const,
  },
];

describe('PlanAccuracyPage', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    get.mockResolvedValue({ success: true, data: { from: 1, to: 2, rows } });
  });

  it('shows planned against actual with a signed deviation', async () => {
    renderWithProviders(<PlanAccuracyPage />, { route: '/admin/reports/plan-accuracy' });

    await waitFor(() => expect(screen.getByText('لیزر فول‌بادی')).toBeInTheDocument());

    expect(screen.getByText('+50٪')).toBeInTheDocument();
    expect(screen.getByText('-3٪')).toBeInTheDocument();
    expect(screen.getByText('زیاد')).toBeInTheDocument();
    expect(screen.getByText('دقیق')).toBeInTheDocument();
  });

  /** نمونهٔ کوچک از گزارش حذف می‌شود؛ صفحه باید همان قاعده را بگوید. */
  it('explains that small samples are excluded', async () => {
    renderWithProviders(<PlanAccuracyPage />, { route: '/admin/reports/plan-accuracy' });

    await waitFor(() =>
      expect(screen.getByText(/کمتر از سه نوبت انجام‌شده در گزارش نمی‌آیند/)).toBeInTheDocument(),
    );
  });
});
