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

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 ClinicDoctorsManager from './ClinicDoctorsManager';

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

beforeEach(() => {
  get.mockReset();
  get.mockImplementation((url: string) => {
    if (url.includes('/clinic/doctor-list/')) return Promise.resolve({ success: true, data: [
      { id: '1', uuid: 'doc-uuid-1', name: 'دکتر رضایی', gender: null, degree: null,
        img: [], specialties: [{ id: '2', name: 'قلب' }], active: true },
    ] });
    if (url.includes('/invitations')) return Promise.resolve({ success: true, data: [
      { uuid: 'inv-1', mobile: '09120000000', invited_name: 'دکتر مهمان', invited_specialty: null,
        status: 'pending', token_used: false, invited_at: 1, expires_at: 9_999_999_999,
        responded_at: null, doctor: null },
    ], meta: { totalRecords: 1, totalPages: 1, currentPage: 1 } });
    return Promise.resolve({ success: true, data: [] });
  });
});

describe('ClinicDoctorsManager', () => {
  it('lists clinic doctors and shows management controls by default', async () => {
    renderWithProviders(<ClinicDoctorsManager clinicUuid="clinic-1" />, { route: '/admin/settings/clinic-doctors' });
    expect(await screen.findByText('دکتر رضایی')).toBeInTheDocument();
    expect(screen.getByText('قلب')).toBeInTheDocument();
    // manager controls
    expect(screen.getByText('دعوت پزشک')).toBeInTheDocument();
    expect(screen.getByTitle('جداسازی از کلینیک')).toBeInTheDocument();
  });

  it('hides every mutating control when readOnly', async () => {
    renderWithProviders(<ClinicDoctorsManager clinicUuid="clinic-1" readOnly />, { route: '/admin/settings/clinic-doctors' });
    expect(await screen.findByText('دکتر رضایی')).toBeInTheDocument();
    expect(screen.queryByText('دعوت پزشک')).not.toBeInTheDocument();
    expect(screen.queryByTitle('جداسازی از کلینیک')).not.toBeInTheDocument();
  });
});
