import { GetSavedSearchesHandler } from '../queries/get-saved-searches/get-saved-searches.handler';
import { GetSavedSearchesQuery } from '../queries/get-saved-searches/get-saved-searches.query';

describe('GetSavedSearchesHandler', () => {
  let handler: GetSavedSearchesHandler;
  let mockPrisma: any;

  const savedSearches = [
    {
      id: 'saved-1',
      userId: 'user-1',
      name: 'Chung cư Q7',
      filters: { district: 'Quan 7' },
      alertEnabled: true,
      lastAlertAt: null,
      createdAt: new Date('2026-01-15'),
    },
    {
      id: 'saved-2',
      userId: 'user-1',
      name: 'Nhà phố Q2',
      filters: { district: 'Quan 2', propertyType: 'HOUSE' },
      alertEnabled: false,
      lastAlertAt: new Date('2026-01-20'),
      createdAt: new Date('2026-01-10'),
    },
  ];

  beforeEach(() => {
    mockPrisma = {
      savedSearch: {
        findMany: vi.fn(),
        count: vi.fn(),
      },
    };

    handler = new GetSavedSearchesHandler(mockPrisma);
  });

  it('returns paginated saved searches', async () => {
    mockPrisma.savedSearch.findMany.mockResolvedValue(savedSearches);
    mockPrisma.savedSearch.count.mockResolvedValue(2);

    const query = new GetSavedSearchesQuery('user-1', 1, 20);
    const result = await handler.execute(query);

    expect(result.data).toHaveLength(2);
    expect(result.total).toBe(2);
    expect(result.page).toBe(1);
    expect(result.limit).toBe(20);
    expect(result.data[0]!.name).toBe('Chung cư Q7');
  });

  it('applies pagination correctly', async () => {
    mockPrisma.savedSearch.findMany.mockResolvedValue([savedSearches[1]]);
    mockPrisma.savedSearch.count.mockResolvedValue(2);

    const query = new GetSavedSearchesQuery('user-1', 2, 1);
    await handler.execute(query);

    expect(mockPrisma.savedSearch.findMany).toHaveBeenCalledWith(
      expect.objectContaining({
        skip: 1,
        take: 1,
      }),
    );
  });

  it('returns empty list when no saved searches', async () => {
    mockPrisma.savedSearch.findMany.mockResolvedValue([]);
    mockPrisma.savedSearch.count.mockResolvedValue(0);

    const query = new GetSavedSearchesQuery('user-1');
    const result = await handler.execute(query);

    expect(result.data).toHaveLength(0);
    expect(result.total).toBe(0);
  });
});
