import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import { of } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
import { TripsList } from './trips-list';
import { TripsApiService } from '../trips-api.service';

describe('TripsList', () => {
  it('renders trip names returned by TripsApiService', async () => {
    const tripsApi = {
      listTrips: vi.fn().mockReturnValue(of([{ id: 't1', name: 'Slovenia 2027' }])),
      createTrip: vi.fn(),
    };

    await TestBed.configureTestingModule({
      imports: [TripsList],
      providers: [{ provide: TripsApiService, useValue: tripsApi }, provideRouter([])],
    }).compileComponents();

    const fixture = TestBed.createComponent(TripsList);
    fixture.detectChanges();
    await fixture.whenStable();
    fixture.detectChanges();

    expect(fixture.nativeElement.textContent).toContain('Slovenia 2027');
  });

  it('calls createTrip when the create form is submitted', async () => {
    const tripsApi = {
      listTrips: vi.fn().mockReturnValue(of([])),
      createTrip: vi.fn().mockReturnValue(of({ id: 't2', name: 'New Trip' })),
    };

    await TestBed.configureTestingModule({
      imports: [TripsList],
      providers: [{ provide: TripsApiService, useValue: tripsApi }, provideRouter([])],
    }).compileComponents();

    const fixture = TestBed.createComponent(TripsList);
    const component = fixture.componentInstance;
    fixture.detectChanges();
    await fixture.whenStable();

    component.newTripName.set('New Trip');
    component.createTrip();

    expect(tripsApi.createTrip).toHaveBeenCalledWith({ name: 'New Trip' });
  });
});
