/*
https://docs.nestjs.com/providers#services
*/

import { Injectable, NotFoundException } from '@nestjs/common';
import { User } from './user.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { UserRegistrationRequestDto } from '../dto/user-registration.req.dto';
import * as bcrypt from 'bcrypt';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
  ) {}

  async doUserRegistration(registerUserData: any): Promise<User> {
    const trimmedPassword = registerUserData.Password.trim();

    const hashedPassword = await bcrypt.hash(trimmedPassword, 10);
    console.log('hash password is : ', hashedPassword);
    const user = new User();
    user.Full_Name = registerUserData.Full_Name;
    user.Email = registerUserData.Email;
    user.Password = hashedPassword;

    return this.userRepository.save(user);
  }

  async getAllUsers(): Promise<User[]> {
    return this.userRepository.find();
  }

  async getUserByEmail(Email: string): Promise<any> {
    return this.userRepository.findOneBy({ Email: Email });
  }

  async updateUser(id: number, userData: any) {
    const getExisting = await this.userRepository.findOneBy({ idUser: id });

    if (!getExisting) {
      throw new NotFoundException();
    }

    getExisting.Full_Name = userData.Full_Name;
    getExisting.Email = userData.Email;
    getExisting.Password = userData.Password;

    await this.userRepository.save(getExisting);
    return { success: true, message: 'user updated successfully' };
  }

  async getUserById(id: number) {
    const getExisting = await this.userRepository.findOneBy({ idUser: id });
    return getExisting;
  }
}
