import { DeleteSavedSearchCommand } from '../commands/delete-saved-search/delete-saved-search.command';
import { DeleteSavedSearchHandler } from '../commands/delete-saved-search/delete-saved-search.handler';

describe('DeleteSavedSearchHandler', () => {
  let handler: DeleteSavedSearchHandler;
  let mockPrisma: any;
  let mockLogger: { log: ReturnType<typeof vi.fn>; warn: ReturnType<typeof vi.fn> };

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

    handler = new DeleteSavedSearchHandler(mockPrisma, mockLogger as any);
  });

  it('deletes a saved search owned by the user', async () => {
    mockPrisma.savedSearch.findUnique.mockResolvedValue({
      id: 'saved-1',
      userId: 'user-1',
      name: 'Test',
    });
    mockPrisma.savedSearch.delete.mockResolvedValue({ id: 'saved-1' });

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

    expect(result.deleted).toBe(true);
    expect(mockPrisma.savedSearch.delete).toHaveBeenCalledWith({ where: { id: 'saved-1' } });
  });

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

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

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

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