import { UsersService } from './users.service';

describe('UsersService.findOrCreateByExternalSubjectId', () => {
  it('creates a new local user on first login', async () => {
    const repo = {
      upsertByExternalSubjectId: jest.fn().mockResolvedValue({
        id: 'u1',
        externalSubjectId: 'sub-1',
        displayName: 'Alex',
        email: 'a@example.com',
        createdAt: new Date(),
        updatedAt: new Date(),
      }),
    };
    const service = new UsersService(repo as never);

    const user = await service.findOrCreateByExternalSubjectId('sub-1', {
      email: 'a@example.com',
      displayName: 'Alex',
    });

    expect(repo.upsertByExternalSubjectId).toHaveBeenCalledWith('sub-1', {
      email: 'a@example.com',
      displayName: 'Alex',
    });
    expect(user.id).toBe('u1');
  });

  it('refreshes displayName/email on subsequent logins without changing the id', async () => {
    const repo = {
      upsertByExternalSubjectId: jest.fn().mockResolvedValue({
        id: 'u1',
        externalSubjectId: 'sub-1',
        displayName: 'Alex Renamed',
        email: 'a@example.com',
        createdAt: new Date(),
        updatedAt: new Date(),
      }),
    };
    const service = new UsersService(repo as never);

    const user = await service.findOrCreateByExternalSubjectId('sub-1', {
      email: 'a@example.com',
      displayName: 'Alex Renamed',
    });

    expect(user.id).toBe('u1');
    expect(user.displayName).toBe('Alex Renamed');
  });
});
