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 {},
}));

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

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

const SUMMARY = {
  enabled: true, share_percent: 5, relations: [],
  today_rials: 500_000, this_month_rials: 3_000_000, total_rials: 9_000_000,
  appointments_count: 4, wallet_balance_rials: 9_000_000,
};

const ROW = {
  uuid: 'e1', appointment_uuid: 'ap1', doctor_name: 'دکتر تست',
  gross_rials: 10_000_000, sms_fee_rials: 0, tax_rials: 0,
  net_after_tax_rials: 10_000_000, share_percent: 5, share_rials: 500_000,
  created_at: 1_700_000_000,
};

function mockEndpoints(summary: Record<string, unknown>, rows: object[] = []) {
  get.mockImplementation((url?: string) => {
    if (url === undefined) return Promise.resolve({ success: true, data: [] });
    if (url.startsWith('/api/v1/secretary/earnings/summary')) {
      return Promise.resolve({ success: true, data: { data: summary } });
    }
    if (url.startsWith('/api/v1/secretary/earnings/report')) {
      return Promise.resolve({ success: true, data: rows, meta: { totalRecords: rows.length, totalPages: 1, currentPage: 1 } });
    }
    return Promise.resolve({ success: true, data: [] });
  });
}

beforeEach(() => get.mockReset());

describe('SecretaryEarningsPage', () => {
  it('کارت‌های درآمد و ردیف گزارش را نشان می‌دهد', async () => {
    mockEndpoints(SUMMARY, [ROW]);
    renderWithProviders(<SecretaryEarningsPage />);

    expect(await screen.findByText('امروز')).toBeInTheDocument();
    expect(screen.getByText('۳۰ روز گذشته')).toBeInTheDocument();
    expect(screen.getByText('موجودی کیف پول')).toBeInTheDocument();
    expect(await screen.findByText('دکتر تست')).toBeInTheDocument();
    expect(screen.getByText('سهم شما')).toBeInTheDocument();
    expect(screen.getByText('۵٪')).toBeInTheDocument();
  });

  it('غیرفعال بودن قابلیت → پیام و بدون جدول', async () => {
    mockEndpoints({ ...SUMMARY, enabled: false });
    renderWithProviders(<SecretaryEarningsPage />);

    await waitFor(() => expect(screen.getByText(/برای شما فعال نیست/)).toBeInTheDocument());
    expect(screen.queryByText('امروز')).not.toBeInTheDocument();
  });
});
