import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';

import { PersonEntity } from './user.entity';
import { UserDTO } from './user.dto';
/*
UserService contains functions for 
- Login
- Register

Both functions return logged in users tokenObject
See more info in UserEntity.

See more info on DTO in it's respective file
*/

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

  async register(data: UserDTO) {
    const { name } = data;
    let user = await this.userRepository.findOne({ where: { name } });
    if (user) {
      throw new HttpException('User already exists', HttpStatus.BAD_REQUEST);
    }
    user = await this.userRepository.create(data);
    await this.userRepository.save(user);
    return user.tokenObject();
  }

  async login(data: UserDTO) {
    const { name, password } = data;
    const user = await this.userRepository.findOne({ where: { name } });
    if (!user) {
      throw new HttpException('User does not exist', HttpStatus.BAD_REQUEST);
    }
    if (!(await user.comparePassword(password))) {
      throw new HttpException('Invalid password', HttpStatus.BAD_REQUEST);
    }
    return user.tokenObject();
  }
}