import {
  BadRequestException,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { RegisterDto } from 'src/auth/Dto/credentials.dto';
import { Neo4jService } from 'src/neo4j/neo4j.service';
import { Node } from 'neo4j-driver';
import { hash } from 'bcrypt';

export type User = Node;

@Injectable()
export class UserService {
  constructor(private readonly neo4jService: Neo4jService) {}

  async findByUsername(username: string): Promise<User> {
    try {
      const res = await this.neo4jService.read(
        `
      MATCH (u:User {username: $username})
      RETURN u
    `,
        { username },
      );
      return res.records[0].get('u');
    } catch (error) {
      throw new UnauthorizedException();
    }
  }

  async create(registerDto: RegisterDto): Promise<User> {
    const hashedPass = await this.hashPass(registerDto.password);
    const newUser = { ...registerDto, password: hashedPass };
    try {
      const res = await this.neo4jService.write(
        `
                CREATE (u:User)
                SET u += $newUser, u.id = randomUUID()
                RETURN u
            `,
        { newUser },
      );
      return res.records[0].get('u');
    } catch (error: any) {
      throw new BadRequestException(error.message);
    }
  }

  async hashPass(plain: string): Promise<string> {
    return await hash(plain, 10);
  }
}
