// @vitest-environment jsdom
import { describe, it, expect, vi, beforeEach } from 'vitest';
import '@testing-library/jest-dom/vitest';
import { render, screen, fireEvent, cleanup } from '@testing-library/react';

vi.mock('../../src/renderer/inbox/api.js', () => ({
  inboxApi: {
    loadOllamaSettings: vi.fn(async () => ({ endpoint: 'http://localhost:11434', model: 'gemma2:2b' })),
    saveOllamaSettings: vi.fn(async () => ({ ok: true })),
    ollamaRecheck: vi.fn(async () => ({ ok: true }))
  }
}));

import { AiProviderSection } from '../../src/renderer/inbox/components/settings/AiProviderSection';

describe('AiProviderSection', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    cleanup();
  });

  it('loads current settings on mount', async () => {
    render(<AiProviderSection />);
    expect(await screen.findByDisplayValue('http://localhost:11434')).toBeInTheDocument();
    expect(screen.getByDisplayValue('gemma2:2b')).toBeInTheDocument();
  });

  it('rejects invalid endpoint URL', async () => {
    render(<AiProviderSection />);
    await screen.findByDisplayValue('http://localhost:11434');
    const input = screen.getByLabelText(/Endpoint/);
    fireEvent.change(input, { target: { value: 'not-a-url' } });
    fireEvent.click(screen.getByRole('button', { name: /저장/ }));
    expect(await screen.findByText(/올바른 URL/)).toBeInTheDocument();
  });

  it('"지금 재확인" calls ollamaRecheck and shows result', async () => {
    const { inboxApi } = await import('../../src/renderer/inbox/api.js');
    render(<AiProviderSection />);
    await screen.findByDisplayValue('http://localhost:11434');
    fireEvent.click(screen.getByRole('button', { name: /지금 재확인/ }));
    expect(inboxApi.ollamaRecheck).toHaveBeenCalled();
  });
});
