import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './entities/user.entity';

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User)
    private readonly usersRepository: Repository<User>,
  ) {}

  findByLoginName(loginName: string) {
    return this.usersRepository
      .createQueryBuilder('user')
      .leftJoinAndSelect('user.roles', 'role')
      .where('user.name = :loginName', { loginName })
      .orWhere('user.email = :loginName', { loginName })
      .getOne();
  }

  findById(id: string) {
    return this.usersRepository.findOne({
      where: { id },
    });
  }

  findByEmail(email: string) {
    return this.usersRepository.findOne({
      where: { email },
    });
  }

  async markLoginSuccess(userId: string) {
    await this.usersRepository.update(userId, {
      lastLoginAt: new Date(),
    });
  }

  async save(user: User) {
    return this.usersRepository.save(user);
  }

  async incrementTokenVersion(userId: string) {
    await this.usersRepository.increment({ id: userId }, 'tokenVersion', 1);
  }
}
