import { describe, it, expect, beforeEach, vi } from 'vitest';
import { screen, fireEvent, 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 AppointmentStatusDropdown from './AppointmentStatusDropdown';

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

beforeEach(() => {
  patch.mockReset();
  patch.mockResolvedValue({ success: true, data: {} });
});

describe('AppointmentStatusDropdown (وضعیت نوبت)', () => {
  it('shows the design label for the current status', () => {
    renderWithProviders(<AppointmentStatusDropdown uuid="a1" currentStatus="confirmed" version={1} queryKey={['x']} />);
    expect(screen.getByText('قطعی شده')).toBeInTheDocument();
  });

  it('offers the day-of workflow targets from confirmed', () => {
    renderWithProviders(<AppointmentStatusDropdown uuid="a1" currentStatus="confirmed" version={1} queryKey={['x']} />);
    fireEvent.click(screen.getByText('قطعی شده'));
    expect(screen.getByText('در حال پیگیری')).toBeInTheDocument();
    expect(screen.getByText('سالن')).toBeInTheDocument();
    expect(screen.getByText('ویزیت شده')).toBeInTheDocument();
  });

  it('patches the status endpoint on selection', async () => {
    renderWithProviders(<AppointmentStatusDropdown uuid="a1" currentStatus="salon" version={2} queryKey={['x']} />);
    fireEvent.click(screen.getByText('سالن'));
    fireEvent.click(screen.getByText('ویزیت شده'));
    await waitFor(() =>
      expect(patch).toHaveBeenCalledWith('/api/v1/appointment/a1/status', { status: 'completed', version: 2 }));
  });

  it('disables terminal statuses', () => {
    renderWithProviders(<AppointmentStatusDropdown uuid="a1" currentStatus="completed" version={1} queryKey={['x']} />);
    expect(screen.getByText('ویزیت شده').closest('button')).toBeDisabled();
  });
});
