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

const navSpy = vi.fn();
vi.mock('react-router-dom', async (orig) => ({
  ...(await orig<typeof import('react-router-dom')>()),
  useNavigate: () => navSpy,
}));
vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
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 { toast } from 'sonner';
import PaymentSuccessPage from './PaymentSuccessPage';

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

beforeEach(() => {
  get.mockReset();
  navSpy.mockReset();
  (toast.error as ReturnType<typeof vi.fn>).mockReset();
  get.mockImplementation((url: string) => {
    if (url.includes('/payment/')) return Promise.resolve({ success: true, data: {
      uuid: 'pay-1', order_id: 'ORD1', amount_rials: 9000000, status: 'success',
      gateway: 'mellat', reference_id: '987654', created_at: 1700000000,
    } });
    if (url.includes('/subscription/my')) return Promise.resolve({ success: true, data: {
      subscription: {
        plan: { name: 'professional', level: 2, max_secretaries: 10, features: { patient_records: true, sms_panel: true } },
        period: { label: 'یک ساله', duration_months: 12 },
        is_trial: false, expires_at: 1710000000, days_remaining: 300,
      },
      used_trial: true, effective_plan: null,
    } });
    return Promise.resolve({ success: true, data: null });
  });
});

describe('PaymentSuccessPage', () => {
  it('shows the receipt and purchased plan on success', async () => {
    renderWithProviders(<PaymentSuccessPage />, { route: '/admin/subscription/success?payment_uuid=pay-1&status=success' });

    expect(await screen.findByText('پرداخت شما با موفقیت انجام شد!')).toBeInTheDocument();
    expect(await screen.findByText('987654')).toBeInTheDocument();               // شماره تراکنش (reference_id)
    expect(await screen.findByText('پلن حرفه‌ای')).toBeInTheDocument();          // purchased plan
    expect(await screen.findByText('پرونده بیمار')).toBeInTheDocument();         // feature label
    expect(navSpy).not.toHaveBeenCalled();
  });

  it('redirects to the plans page with an error toast on non-success status', () => {
    renderWithProviders(<PaymentSuccessPage />, { route: '/admin/subscription/success?payment_uuid=pay-1&status=failed' });

    expect(navSpy).toHaveBeenCalledWith('/admin/subscription', { replace: true });
    expect(toast.error).toHaveBeenCalled();
  });
});
