import { fireEvent,render,screen,waitFor } from '@testing-library/react';
import { toast } from 'react-hot-toast';
import { beforeEach,describe,expect,it,vi } from 'vitest';
import api from '../services/api';
import PrescriptionsManager from './PrescriptionsManager';
vi.mock('../services/api', () => ({ default: { get: vi.fn(), patch: vi.fn() }, BASE_DOMAIN: 'https://api.example.com' }));
vi.mock('react-hot-toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
const rx = { id: 'rx-12345678', status: 'PENDING', fileUrl: '/uploads/rx.jpg', notes: 'Patient note', adminNotes: 'Prior note\n__PRESCRIBED_PRODUCTS__:["p1"]', createdAt: '2026-03-01', user: { firstName: 'Owner', lastName: 'One', mobile: '09120000000' }, pet: { name: 'Milo', type: 'گربه', breed: 'Persian', age: 2, weight: 3 } };
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(api.get).mockImplementation(async url => ({ data: url === '/prescriptions' ? { data: [rx] } : { data: [{ id: 'p1', name: 'Supplement', price: 100 }] } }));
vi.mocked(api.patch).mockResolvedValue({ data: {} });
});
async function open() { render(); fireEvent.click(await screen.findByRole('button', { name: 'بررسی و تجویز' })); }
function submit() { fireEvent.submit(document.getElementById('prescriptionForm')!); }
describe('PrescriptionsManager', () => {
it('renders owner and pet data and filters by clinical status', async () => {
render();
expect(await screen.findByText('Owner One')).toBeInTheDocument();
expect(screen.getByText('Milo (Persian)')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'رد شده' }));
expect(screen.getByText('هیچ نسخهای با این فیلتر یافت نشد')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'همه' }));
expect(screen.getByText('Patient note')).toBeInTheDocument();
});
it('restores encoded products and trims clinical notes on approval', async () => {
await open();
expect(screen.getByRole('textbox')).toHaveValue('Prior note');
fireEvent.change(screen.getByRole('textbox'), { target: { value: ' Take daily ' } });
submit();
await waitFor(() => expect(api.patch).toHaveBeenCalledWith('/prescriptions/rx-12345678/review', { status: 'APPROVED', adminNotes: 'Take daily\n__PRESCRIBED_PRODUCTS__:["p1"]' }));
await waitFor(() => expect(document.getElementById('prescriptionForm')).not.toBeInTheDocument());
expect(api.get).toHaveBeenCalledTimes(3);
});
it.each([['عدم تایید / ناخوانا', 'REJECTED'], ['در انتظار پیگیری بیمار', 'PENDING']])('submits decision %s without deselected products', async (label, status) => {
await open(); fireEvent.click(screen.getByRole('button', { name: label }));
fireEvent.click(screen.getByText('Supplement'));
fireEvent.change(screen.getByRole('textbox'), { target: { value: ' ' } }); submit();
await waitFor(() => expect(api.patch).toHaveBeenCalledWith('/prescriptions/rx-12345678/review', { status, adminNotes: undefined }));
});
it('retains review and notes when update fails', async () => {
vi.mocked(api.patch).mockRejectedValue(new Error('offline')); await open(); submit();
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('خطا در تغییر وضعیت نسخه پزشکی'));
expect(screen.getByRole('textbox')).toHaveValue('Prior note'); expect(toast.success).not.toHaveBeenCalled();
});
it('handles initial prescription failure', async () => {
vi.mocked(api.get).mockRejectedValue(new Error('offline')); render();
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('خطا در بارگذاری اطلاعات'));
expect(await screen.findByText('هیچ نسخهای با این فیلتر یافت نشد')).toBeInTheDocument();
});
it('allows review when optional products fail', async () => {
vi.mocked(api.get).mockImplementation(async url => { if (url !== '/prescriptions') throw new Error('products offline'); return { data: [rx] }; });
await open(); expect(screen.getByRole('textbox')).toHaveValue('Prior note'); expect(toast.error).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('button', { name: 'انصراف' })); expect(api.patch).not.toHaveBeenCalled();
});
});