// Validation tests for the shared TripForm component.
import { render, screen, fireEvent } from '@testing-library/react';
import TripForm, { validateTripForm } from '../components/TripForm';
import { TripFormData } from '../models/trip';

const validValues: TripFormData = {
  code: 'GALR210214',
  name: 'Gale Reef',
  length: '4 nights / 5 days',
  start: '2026-02-14',
  resort: 'Emerald Bay, 3 stars',
  perPerson: '799.00',
  image: 'reef1.jpg',
  description: 'Sed et augue lorem.'
};

describe('validateTripForm', () => {
  test('returns no invalid fields for a complete trip', () => {
    expect(validateTripForm(validValues)).toEqual([]);
  });

  test('flags every empty required field', () => {
    const invalid = validateTripForm({ ...validValues, code: '', name: ' ' });
    expect(invalid).toContain('code');
    expect(invalid).toContain('name');
    expect(invalid).toHaveLength(2);
  });
});

describe('TripForm', () => {
  test('blocks submission and shows messages when fields are empty', () => {
    const onSubmit = jest.fn().mockResolvedValue(undefined);
    render(<TripForm title="Add Trip" onSubmit={onSubmit} />);

    fireEvent.click(screen.getByRole('button', { name: 'Save' }));

    expect(onSubmit).not.toHaveBeenCalled();
    expect(screen.getByText('Trip Code is required')).toBeInTheDocument();
    expect(screen.getByText('Name is required')).toBeInTheDocument();
  });

  test('submits the entered values when the form is valid', () => {
    const onSubmit = jest.fn().mockResolvedValue(undefined);
    render(
      <TripForm title="Edit Trip" initialValues={validValues} onSubmit={onSubmit} />
    );

    fireEvent.click(screen.getByRole('button', { name: 'Save' }));

    expect(onSubmit).toHaveBeenCalledWith(validValues);
  });
});
