// @vitest-environment jsdom
/**
 * Component tests for AuthForm (settings → auth.*).
 *
 * Focus: render with realistic config, the primary-provider <select>, the
 * adminEmails StringArrayEditor, and the sessionMaxAge number serialization
 * (string → Number, empty → undefined). Network is not used by this form
 * (pure SectionFormProps presentational component).
 */
import '../../test/dom-setup';
import { beforeAll, describe, it, expect, vi } from 'vitest';
import { screen, fireEvent } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { renderWithProviders } from '../../test/render-helpers';
import i18n from '../../i18n';
import { AuthForm } from './AuthForm';

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

const noEnv = {};

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

describe('AuthForm', () => {
  it('renders provider fields with realistic existing config', () => {
    render({
      auth: {
        primaryProvider: 'gitea',
        adminEmails: ['root@example.com'],
        providers: { gitea: { baseUrl: 'https://gitea.example.com', clientId: 'cid' } },
      },
    });
    // primary provider select reflects stored value
    const select = screen.getByDisplayValue('gitea only') as HTMLSelectElement;
    expect(select.value).toBe('gitea');
    // existing admin email chip rendered by StringArrayEditor
    expect(screen.getByText('root@example.com')).toBeInTheDocument();
    // gitea base url field carries the stored value
    expect(screen.getByDisplayValue('https://gitea.example.com')).toBeInTheDocument();
  });

  it('emits auth.primaryProvider when the select changes', async () => {
    const user = userEvent.setup();
    const onChange = render({ auth: {} });
    const select = screen.getByDisplayValue('(none — all enabled)');
    await user.selectOptions(select, 'google');
    expect(onChange).toHaveBeenCalledWith('auth.primaryProvider', 'google');
  });

  it('serializes sessionMaxAge to a Number', () => {
    const onChange = render({ auth: {} });
    const input = screen.getByRole('spinbutton'); // type=number FieldInput
    fireEvent.change(input, { target: { value: '86400000' } });
    expect(onChange).toHaveBeenCalledWith('auth.sessionMaxAge', 86400000);
  });

  it('clears sessionMaxAge to undefined when emptied', () => {
    const onChange = render({ auth: { sessionMaxAge: 86400000 } });
    const input = screen.getByDisplayValue('86400000');
    fireEvent.change(input, { target: { value: '' } });
    expect(onChange).toHaveBeenLastCalledWith('auth.sessionMaxAge', undefined);
  });

  it('adds an admin email through the StringArrayEditor', async () => {
    const user = userEvent.setup();
    const onChange = render({ auth: { adminEmails: [] } });
    const textInput = screen.getByPlaceholderText('admin@example.com');
    await user.type(textInput, 'new@example.com');
    await user.keyboard('{Enter}');
    expect(onChange).toHaveBeenCalledWith('auth.adminEmails', ['new@example.com']);
  });

  it('toggles the secureCookie checkbox', async () => {
    const user = userEvent.setup();
    const onChange = render({ auth: {} });
    const checkboxes = screen.getAllByRole('checkbox');
    await user.click(checkboxes[0]); // secureCookie is the first checkbox
    expect(onChange).toHaveBeenCalledWith('auth.secureCookie', true);
  });
});
