import { GetSavedSearchHandler } from '../queries/get-saved-search/get-saved-search.handler';
import { GetSavedSearchQuery } from '../queries/get-saved-search/get-saved-search.query';

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

  const existingSearch = {
    id: 'saved-1',
    userId: 'user-1',
    name: 'Chung cư Q7',
    filters: { district: 'Quan 7' },
    alertEnabled: true,
    lastAlertAt: null,
    createdAt: new Date('2026-01-15'),
  };

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

    handler = new GetSavedSearchHandler(mockPrisma);
  });

  it('returns saved search detail for the owner', async () => {
    mockPrisma.savedSearch.findUnique.mockResolvedValue(existingSearch);

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

    expect(result.id).toBe('saved-1');
    expect(result.name).toBe('Chung cư Q7');
    expect(result.alertEnabled).toBe(true);
  });

  it('throws NotFoundException when saved search does not exist', async () => {
    mockPrisma.savedSearch.findUnique.mockResolvedValue(null);

    const query = new GetSavedSearchQuery('non-existent', 'user-1');
    await expect(handler.execute(query)).rejects.toThrow();
  });

  it('throws ForbiddenException when user does not own the saved search', async () => {
    mockPrisma.savedSearch.findUnique.mockResolvedValue({
      ...existingSearch,
      userId: 'other-user',
    });

    const query = new GetSavedSearchQuery('saved-1', 'user-1');
    await expect(handler.execute(query)).rejects.toThrow('Bạn không có quyền xem tìm kiếm này');
  });
});
