// @vitest-environment jsdom
/**
 * Component tests for MetricsForm (settings → llm.metrics.* + gateway.metrics.*).
 *
 * Focus: the two MetricsBlock instances write to distinct config paths,
 * checkbox + text serialization (empty → undefined), and reading nested
 * existing values.
 */
import '../../test/dom-setup';
import { beforeAll, describe, it, expect, vi } from 'vitest';
import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { renderWithProviders } from '../../test/render-helpers';
import i18n from '../../i18n';
import { MetricsForm } from './MetricsForm';

beforeAll(async () => {
  await i18n.changeLanguage('en');
});

function render(config: any, onChange = vi.fn()) {
  renderWithProviders(
    <MetricsForm config={config} onChange={onChange} overriddenByEnv={{}} />,
  );
  return onChange;
}

describe('MetricsForm', () => {
  it('reads nested enabled state for each block independently', () => {
    render({
      llm: { metrics: { enabled: true } },
      gateway: { metrics: { enabled: false } },
    });
    const enableBoxes = screen.getAllByLabelText('Enable') as HTMLInputElement[];
    expect(enableBoxes).toHaveLength(2);
    expect(enableBoxes[0].checked).toBe(true); // worker (llm.metrics)
    expect(enableBoxes[1].checked).toBe(false); // gateway.metrics
  });

  it('toggles the worker-metrics enable checkbox to llm.metrics.enabled', async () => {
    const user = userEvent.setup();
    const onChange = render({});
    const enableBoxes = screen.getAllByLabelText('Enable');
    await user.click(enableBoxes[0]);
    expect(onChange).toHaveBeenCalledWith('llm.metrics.enabled', true);
  });

  it('toggles the gateway-metrics enable checkbox to gateway.metrics.enabled', async () => {
    const user = userEvent.setup();
    const onChange = render({});
    const enableBoxes = screen.getAllByLabelText('Enable');
    await user.click(enableBoxes[1]);
    expect(onChange).toHaveBeenCalledWith('gateway.metrics.enabled', true);
  });

  it('serializes a cleared prefix to undefined', async () => {
    const user = userEvent.setup();
    const onChange = render({ llm: { metrics: { prefix: 'aao_worker' } } });
    const prefixInput = screen.getByDisplayValue('aao_worker');
    await user.clear(prefixInput);
    expect(onChange).toHaveBeenLastCalledWith('llm.metrics.prefix', undefined);
  });
});
