import type { UsersRepository } from './users.repository.js';
import type { AuthUser } from '../../common/types.js';
import { NotFoundError } from '../../common/errors.js';

interface Deps {
  usersRepository: UsersRepository;
}

export class UsersService {
  private readonly usersRepository: UsersRepository;

  public constructor({ usersRepository }: Deps) {
    this.usersRepository = usersRepository;
  }

  public async syncFromToken(user: AuthUser) {
    return this.usersRepository.upsertFromToken(user.keycloakId, user.email, user.displayName);
  }

  public async getProfile(keycloakId: string) {
    const user = await this.usersRepository.findByKeycloakId(keycloakId);
    if (!user) {
      throw new NotFoundError('User not found');
    }
    return user;
  }
}
