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 {},
}));
vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));

import { api } from '../lib/api';
import ServiceInsuranceModal from './ServiceInsuranceModal';
import type { ServiceItem } from '../types';

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

const item = { uuid: 'svc-1', name: 'سرم ۵۰۰cc' } as ServiceItem;

beforeEach(() => {
  vi.clearAllMocks();
  get.mockImplementation((url: string) => {
    if (url.includes('service-coverage')) return Promise.resolve({ data: { data: [] } });
    return Promise.resolve({
      data: { data: [{ uuid: 'ins-1', insurance_name: 'بیمه ایران', insurance_kind: 'basic', coverage_percent: 70 }] },
    });
  });
  put.mockResolvedValue({ success: true });
});

const percentInput = async () => {
  const el = await screen.findByPlaceholderText('ارث از قرارداد');
  return el as HTMLInputElement;
};

describe('ServiceInsuranceModal — فیلد درصد پوشش', () => {
  it('رقم فارسی را می‌پذیرد و NaN نمایش نمی‌دهد', async () => {
    renderWithProviders(<ServiceInsuranceModal item={item} onClose={() => {}} />);
    const input = await percentInput();

    fireEvent.change(input, { target: { value: '۲۵' } });

    expect(input.value).toBe('25');
    expect(input.value).not.toContain('NaN');
  });

  it('مقدار ذخیره‌شده عدد معتبر است', async () => {
    renderWithProviders(<ServiceInsuranceModal item={item} onClose={() => {}} />);
    fireEvent.change(await percentInput(), { target: { value: '۳۰' } });
    fireEvent.click(screen.getByRole('button', { name: 'ذخیره' }));

    await waitFor(() => expect(put).toHaveBeenCalled());
    expect(put.mock.calls[0][1]).toMatchObject({ service_item_uuid: 'svc-1', coverage_percent: 30 });
  });

  it('بیش از ۱۰۰ به ۱۰۰ محدود می‌شود', async () => {
    renderWithProviders(<ServiceInsuranceModal item={item} onClose={() => {}} />);
    fireEvent.change(await percentInput(), { target: { value: '۱۵۰' } });
    fireEvent.click(screen.getByRole('button', { name: 'ذخیره' }));

    await waitFor(() => expect(put).toHaveBeenCalled());
    expect(put.mock.calls[0][1]).toMatchObject({ coverage_percent: 100 });
  });

  it('فیلد خالی → null (ارث از قرارداد)', async () => {
    renderWithProviders(<ServiceInsuranceModal item={item} onClose={() => {}} />);
    const input = await percentInput();
    fireEvent.change(input, { target: { value: '۴۰' } });
    fireEvent.change(input, { target: { value: '' } });

    expect(input.value).toBe('');
    fireEvent.click(screen.getByRole('button', { name: 'ذخیره' }));
    await waitFor(() => expect(put).toHaveBeenCalled());
    expect(put.mock.calls[0][1]).toMatchObject({ coverage_percent: null });
  });

  it('حروف نامعتبر وارد نمی‌شود', async () => {
    renderWithProviders(<ServiceInsuranceModal item={item} onClose={() => {}} />);
    const input = await percentInput();
    fireEvent.change(input, { target: { value: 'ابج' } });

    expect(input.value).toBe('');
  });
});
