// @vitest-environment jsdom
/**
 * Component tests for PathsStorageForm (settings → storage.*).
 *
 * Focus: text path passthrough (empty → undefined), numeric serialization
 * with defaults (taskUploadMaxSizeMb default 50, trashRetentionDays default
 * 30), and ENV-override gating that disables the worktree field.
 */
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 { PathsStorageForm } from './PathsStorageForm';

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

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

describe('PathsStorageForm', () => {
  it('renders existing storage values and numeric defaults', () => {
    render({ storage: { worktreeDir: '/srv/worktrees' } });
    expect(screen.getByDisplayValue('/srv/worktrees')).toBeInTheDocument();
    // defaults appear when unset
    expect(screen.getByDisplayValue('50')).toBeInTheDocument(); // taskUploadMaxSizeMb default
    expect(screen.getByDisplayValue('30')).toBeInTheDocument(); // trashRetentionDays default
  });

  it('writes storage.customPiecesDir, undefined when cleared', async () => {
    const user = userEvent.setup();
    const onChange = render({ storage: { customPiecesDir: '/old' } });
    const input = screen.getByDisplayValue('/old');
    await user.clear(input);
    expect(onChange).toHaveBeenLastCalledWith('storage.customPiecesDir', undefined);
  });

  it('serializes trashRetentionDays as a Number', () => {
    const onChange = render({ storage: {} });
    // default render shows 30
    const input = screen.getByDisplayValue('30');
    fireEvent.change(input, { target: { value: '7' } });
    expect(onChange).toHaveBeenCalledWith('storage.trashRetentionDays', 7);
  });

  it('disables the worktree field when overridden by env', () => {
    render({ storage: { worktreeDir: '/srv/worktrees' } }, { 'storage.worktreeDir': true });
    const input = screen.getByDisplayValue('/srv/worktrees') as HTMLInputElement;
    expect(input.disabled).toBe(true);
  });

  it('supports the legacy flat worktreeDir env override key', () => {
    render({ storage: { worktreeDir: '/srv/worktrees' } }, { worktreeDir: true });
    const input = screen.getByDisplayValue('/srv/worktrees') as HTMLInputElement;
    expect(input.disabled).toBe(true);
  });
});
