import { act, renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { tripPlacesApi } from '@/db/api';
import { useTripPlaces } from '../useTripPlaces';

// Mocking dependencies
vi.mock('@/hooks/use-toast', () => ({
  useToast: () => ({
    toast: vi.fn(),
  }),
}));

vi.mock('@/db/api', () => ({
  tripPlacesApi: {
    addToDay: vi.fn(),
    remove: vi.fn(),
    updatePlacesOrder: vi.fn(),
  },
}));

describe('useTripPlaces', () => {
  const mockTrip = {
    id: 'trip-1',
    days: [
      {
        id: 'day-1',
        dayNumber: 1,
        places: [{ id: 'place-1', tripPlaceId: 'tp-1', name: 'Test Place', order_index: 0 }],
      },
    ],
  } as any;

  const mockLoadTrip = vi.fn();

  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('should return activeDayPlaces correctly', () => {
    const { result } = renderHook(() => useTripPlaces(mockTrip, 'day-1', mockLoadTrip));
    expect(result.current.activeDayPlaces).toHaveLength(1);
    expect(result.current.activeDayPlaces[0].name).toBe('Test Place');
  });

  it('should call addToDay when addPlace is called', async () => {
    const { result } = renderHook(() => useTripPlaces(mockTrip, 'day-1', mockLoadTrip));
    
    await act(async () => {
      await result.current.addPlace('new-place-id', 'day-1');
    });

    expect(tripPlacesApi.addToDay).toHaveBeenCalledWith(expect.objectContaining({
      trip_day_id: 'day-1',
      place_id: 'new-place-id',
    }));
    expect(mockLoadTrip).toHaveBeenCalledWith('trip-1');
  });

  it('should call remove when removePlace is called', async () => {
    const { result } = renderHook(() => useTripPlaces(mockTrip, 'day-1', mockLoadTrip));
    
    await act(async () => {
      await result.current.removePlace('tp-1');
    });

    expect(tripPlacesApi.remove).toHaveBeenCalledWith('tp-1');
    expect(mockLoadTrip).toHaveBeenCalledWith('trip-1');
  });
});
