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';

@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) {
        try{
            const { name, password } = data;
            const user = await this.userRepository.findOne({ where: { name }});
            if (!user || !(await user.comparePassword(password))) {
                throw new HttpException(
                    'Invalid username/password',
                    HttpStatus.BAD_REQUEST,
                );
            }
            return user.tokenObject();
        }catch(error){
            return error.message;
        }
    }

}