import { FakeUserRepository } from '@app/testing/domain/users/fake-user.repository';
import { PbUserRepository } from '@app/infrastructure/users/pb-user.repository';
import { mockUsers } from '@app/testing/user.mock';
import PocketBase from 'pocketbase';

jest.mock('pocketbase');

describe('UserRepository', () => {
  let userRepo: FakeUserRepository;
  let mockCollection: any;
  let mockPocketBase: any;

  beforeEach(() => {
    mockPocketBase = {
      collection: jest.fn().mockReturnValue({
        update: jest.fn(),
        getOne: jest.fn(),
      }),
    };

    // 👇 On remplace la classe importée par notre version mockée
    (PocketBase as jest.Mock).mockImplementation(() => mockPocketBase);

    // on récupère une "collection" simulée
    mockCollection = mockPocketBase.collection('users');

    // on instancie le repository à tester
    userRepo = new PbUserRepository();
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  // TODO: revoir la logique de test
  it('devrait appeler pb.collection("users").getFirstListItem()  ', () => {
    const userId = 'user_001';

    mockCollection.getOne.mockResolvedValue(mockUsers.find((u) => u.id === userId));

    userRepo.getUserById(userId).subscribe((result) => {
      expect(mockCollection.getOne).toHaveBeenCalledWith(userId);
      expect(result).toEqual(mockUsers[0]);
    });
  });

  it('devrait appeler pb.collection("users").update() avec ID et data ', () => {
    const userId = 'user_001';
    const data = { email: 'bar@foo.com' };
    const updatedUser = { ...mockUsers[0], email: data.email };
    mockCollection.update.mockResolvedValue(updatedUser);

    userRepo.update(userId, data).subscribe((result) => {
      expect(mockCollection.update).toHaveBeenCalledWith(userId, data);
      expect(result.email).toBe(data.email);
    });
  });
});
