import { TestBed } from '@angular/core/testing';
import { ActivatedRoute } from '@angular/router';
import { of } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
import { TripDetail } from './trip-detail';
import { TripsApiService } from '../trips-api.service';

describe('TripDetail', () => {
  it('renders the trip name and members for the routed tripId', async () => {
    const tripsApi = {
      getTrip: vi.fn().mockReturnValue(of({ id: 't1', name: 'Slovenia 2027', version: 1 })),
      listMembers: vi.fn().mockReturnValue(of([{ id: 'm1', userId: 'u1', role: 'OWNER', status: 'ACTIVE' }])),
      updateTrip: vi.fn(),
    };

    await TestBed.configureTestingModule({
      imports: [TripDetail],
      providers: [
        { provide: TripsApiService, useValue: tripsApi },
        { provide: ActivatedRoute, useValue: { snapshot: { paramMap: { get: () => 't1' } } } },
      ],
    }).compileComponents();

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

    expect(tripsApi.getTrip).toHaveBeenCalledWith('t1');
    expect(tripsApi.listMembers).toHaveBeenCalledWith('t1');
    expect(fixture.nativeElement.textContent).toContain('Slovenia 2027');
  });

  it('shows a plain error message on a 409 optimistic-locking conflict', async () => {
    const tripsApi = {
      getTrip: vi.fn().mockReturnValue(of({ id: 't1', name: 'Slovenia 2027', version: 1 })),
      listMembers: vi.fn().mockReturnValue(of([])),
      updateTrip: vi.fn().mockReturnValue({
        subscribe: (observer: { error: (err: unknown) => void }) => observer.error({ status: 409 }),
      }),
    };

    await TestBed.configureTestingModule({
      imports: [TripDetail],
      providers: [
        { provide: TripsApiService, useValue: tripsApi },
        { provide: ActivatedRoute, useValue: { snapshot: { paramMap: { get: () => 't1' } } } },
      ],
    }).compileComponents();

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

    component.rename('New name');

    expect(component.conflictError()).toBe(true);
  });
});
