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

const navigate = vi.fn();
vi.mock('react-router', async (orig) => ({
  ...(await orig<typeof import('react-router')>()),
  useNavigate: () => navigate,
}));
vi.mock('../lib/api', () => ({ api: { get: vi.fn() }, ApiError: class extends Error {} }));

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

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

const ROWS = [
  { uuid: 'pay-1', amount: 1500000, status: 'success', gateway: 'mellat', ref_id: '99123',
    origin: 'nobat724.com', patient_mobile: '09120000001', appointment_uuid: null,
    paid_at: '2026-08-19T10:00:00+00:00', created_at: '2026-08-19T09:55:00+00:00' },
  // پرداخت‌های قدیمی آدرس بازگشت ندارند و مبدأشان ناشناخته است.
  { uuid: 'pay-2', amount: 900000, status: 'failed', gateway: 'mellat', ref_id: null,
    origin: null, patient_mobile: '09120000002', appointment_uuid: null,
    paid_at: null, created_at: '2026-08-18T09:00:00+00:00' },
];

beforeEach(() => {
  navigate.mockReset();
  get.mockReset();
  get.mockResolvedValue({ success: true, data: ROWS, meta: { totalRecords: 2, totalPages: 1, currentPage: 1 } });
});

describe('PaymentsPage (پرداخت‌های ادمین)', () => {
  it('دامنهٔ مبدأ هر پرداخت را نشان می‌دهد', async () => {
    renderWithProviders(<PaymentsPage />, { route: '/admin/payments' });

    expect(await screen.findByText('nobat724.com')).toBeInTheDocument();
    expect(screen.getByText('مبدأ')).toBeInTheDocument();
  });

  it('جستجو دامنه را هم به سرور می‌فرستد', async () => {
    renderWithProviders(<PaymentsPage />, { route: '/admin/payments?search=nobat724.com' });

    await waitFor(() =>
      expect(get).toHaveBeenCalledWith(expect.stringContaining('search=nobat724.com')),
    );
  });
});
